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?
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.