JavaScript have a variable in a variable name [duplicate] - javascript

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
I have a variable varName, which has the contents of "myvar". I want to create a variable that has the name of variable and the contents of varName, so the name would be variablemyVar.
How do I do this?

You can do
window["variable" + varName] = 42;
console.log(variablemyvar); // 42
This will make the variable global. Instead of window, you can use any scope (object), i.e.
var myObject = {
someOtherVariable: 1337
};
myObject["variable" + varName] = 42;
console.log(myObject.variablemyvar); // 42
However, you should avoid doing this altogether whenever possible. The reason for this is that code like this breaks easy – say you want to rename the variable later on. Most likely you will overlook this, even the IDEs will. Another reason is that code minifiers will fail to minify this, if you set them to be "aggressive", it will even break the code during minification.
Lastly, especially using the first example with window, global variables are considered bad practice and should always be avoided, no matter how you declare them.

Related

Which has better performance?Accesing global variable directly from a function or assigning it to another variable? [duplicate]

This question already has answers here:
How do you performance test JavaScript code?
(24 answers)
Closed 2 years ago.
Here I have two examples of accessing global variables;
basic example of my global variable
globalVar:any={
a:5,
b:3,
c:4
}
Ex.1
function accesVar(){
return this.globalVar.a*=2
}
Ex.2
function accesVar(){
let _var=this.globalVar.a;
return _var*=2
}
In this example global variable doesnt seem a good practise and I dont use them when I dont need to share variables with more than one function.Considering in general and real world(much bigger data),which would be best approach and has better performance?
Both have different importance.
Example one is direct use of globle variable. Saves you extra declaration.
Example two is useful when we need to use the global value many times inside the function.

JavaScript function not working when passing variable instead of hard coded value [duplicate]

This question already has answers here:
Using a string to access a variable
(3 answers)
Closed 3 years ago.
I have a JS function as below
// A simple array where we keep track of things that are filed.
filed = [];
function fileIt(thing) {
// Dynamically call the file method of whatever 'thing' was passed in.
thing.file();
// Mark as filed
filed.push(thing);
}
Now, function fileIt(thing) is working well when called as below
fileIt(AuditForm);
Whereas, its giving error at line thing.file(); when i am trying to pass a variable like below
var formID = obj.id;
fileIt(formID);
Variable formID has same value and i.e. "AuditForm" what's wrong here. Kindly suggest.
If obj.id is the string AuditForm, then you have no choice but to use dynamic property notation on the global window object, or use eval if you didn't declare AuditForm with var on the global scope:
If you declare AuditForm with var on the global scope:
fileIt(window[formID]);
If you don't:
fileIt(eval(formID));
Do note that eval is a very poor option, as if obj.id can be interpreted as other code, e.g. another eval call which will be evaluated, then malicious operations can be performed. Example:
const obj = {
id: "eval('alert(\"Inside an eval script!\")')"
};
eval(obj.id);

Define & assign variable with function Node [duplicate]

This question already has answers here:
Does node.js have equivalent to window object in browser
(2 answers)
Closed 6 years ago.
I know with browser-run JavaScript, I could use window[varName]=value; to set global variables. I seem to remember there being a function to accomplish this in Node JS, but I'm not sure what it is.
If it helps, I'm aiming to set all the properties of an object as separate own variables.
In Node.js the global variables are stored in the global object, I think...
Then it'd be so:
global[varName] = value;
// or...
global.varName = value;
I think you're confusing something. Maybe you want to initialize a object constructor expression.
{ property: "string, or anything else" }
// this expression returns a object that can be assigned
// everywhere, but when assigned, turns a reference
If you want to get/set properties in this object you must do the same thing you were doing before, index the object with the keys [...] or ., then you can optionally assign (set) the object's property with =, else it'll be returned.

Javascript use variable name to thread a function? [duplicate]

This question already has answers here:
Use JavaScript variable as function name?
(5 answers)
Closed 7 years ago.
In GSC, you are able to make a variable become the name of a function that you thread. It looks like this:
variable = "pizza";
[[variable]]();
the engine then reads it like:
pizza();
my question is, is it possible to do that in javascript as easily or do I have to make if/else/switch statements for it?
my question is, is it possible to do that in javascript as easily or
do I have to make if/else/switch statements for it?
If you want to use the safe, fail-proof way, then you can access such variables only in two contexts.
If the variable is in global context, in the case of which, you can do window[variable]();
Else if the variable is a property of an object, in the case of which, you can do obj_name[variable](), basically anything that can be accessed via bracket notation. window is an object too.
Then there's always the dirty way:
You can use highly evil eval like eval(variable + "()") or you can use the Function constructor in the same way. Note however that both the methods can be misused and are highly advised against.

How do I access a local variable dynamically (via a String form of its name) from a closure scope? [duplicate]

This question already has answers here:
How can I access local scope dynamically in javascript?
(4 answers)
Closed 8 years ago.
In Javascript, I'm used to being able to access variables within a known namespace "dynamically" (correct me if I'm using the wrong word here) by using the [] operator. For instance (from the global namespace):
var a = 1;
window['a']; # => 1
Or from a object-type namespace:
var a = { b: 1 };
a['b']; # => 1
And I'm familiar with the basics of how this is determined:
var a = function(){ return this['c']; };
var b = { c: 1 };
a.apply(b); # => 1;
But within a function itself, how do I access local variables I've just instantiated (or redefined) using var?
Namely, I want the following function call to return 1 but without calling a:
function(){
var a = 1;
return a;
}
You can't use window['a'] because a is defined locally, and you can't use this['a'] because this changes depending on the context from which the function is called.
In a realistic setting, I'd simply refactor to avoid dynamically creating and accessing local variables because it's generally a bad idea anyway, but as an academic question, I'm curious as to whether it's possible to access a via its string name at all.
You're mixing up local variables (which are not properties of an object) with properties (which are not local variables). There is no answer to your question, or, rather, the answer is "it can't be done".

Categories

Resources