9

Lets say I have an array of names for a variable:

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

How do I create var name1, var name2 and var name3 by just looping through the varNames array?

1
  • 2
    It's usually not a good idea to create global variables dynamically. Perhaps if you described the bigger picture someone might be able to suggest a better approach. Commented Aug 4, 2012 at 8:54

3 Answers 3

14

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 could create variables within a custum object:

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

[ES20xx]

const myVariables = ['name1', 'name2', 'name3']
  .reduce( (a, v, i) => ({...a, [v]: i + 1 }), {});

console.log(JSON.stringify(myVariables, null, 2));

// to 'global' variables
Object.entries(myVariables).forEach( ([key, value]) =>
  window[key] = value );
  
console.log(`name1: ${name1}, name2: ${name2}`);

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a reason you use i+=1 instead of i++?
It's taken from Douglas Crockford. He advises against using the ++ operator to avoid confusion like: var i = 5; var j = i++; /* j is now 5 and i is 6 */ var k = ++i; /* k is now 7 and i is 7 */
Your 2017 addition no longer answers the original question. Still useful to be aware of that syntax, but that is for something else :)
2

You can do it as follows. I added the alerts to prove you can set a value to those 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);

Comments

2

The direct answer to your question would be - you can do it using 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"
}

Please note though this is considered bad practice and usually there is no justification for using eval for such case. Also note that it's more common to create array using following style:

var varNames = ["name1", "name2", "name3"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.