How to dynamically create javascript variables from an array?

Suppose I have an array of names for a variable:

var varNames = new Array("name1","name2","name3");

How to create var name1, var name2and var name3by a simple array loop varNames?

+5
source share
3 answers

This will create global variables (in the global namespace, i.e. window).

var varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
  window[varNames[i]] = 0;
}
name1; //=> 0

Since using global variables is considered bad practice, you can create variables inside the custum object:

var myVariables = {}
   ,varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
  myVariables[varNames[i]] = 0;
}
myVariables.name1; //=> 0

Change 2017

Using es≥6:

const [v1, v2, v3] = ["name1","name2","name3"];
console.log(v1); // => name1
+6
source

You can do it as follows. I added warnings to prove that you can set a value for these variables.

var varNames = new Array("name1","name2","name3");
for(var i = 0; i < varNames.length; i++) {
    window[varNames[i]] = i;
}
alert("name1: " + name1);
alert("name2: " + name2);
alert("name3: " + name3);
+2
source

: eval:

var varNames = new Array("name1","name2","name3");

for (var i=0; i<varNames.length; i++) {
    var varName = varNames[i];
    eval("var "+varName); // would be "var name1"
}

Note that this is considered bad practice, and there is usually no excuse for using eval for such a case. Also note that the following style is often used to create an array:

var varNames = ["name1", "name2", "name3"];
+1
source

All Articles