71

How can I use a for loop to dynamically create variables, and be returned.

function createVariables()
{
for ( i=0; i<=20; i++ )
 {
 var account = i;
 return var account + i;
 }
 }

The goal is to have the result below:

var account1;
var account2;
var account3; and etc.....
asked Jul 11, 2011 at 1:56
0

12 Answers 12

119

You should use an array:

function createVariables(){
 var accounts = [];
 for (var i = 0; i <= 20; ++i) {
 accounts[i] = "whatever";
 }
 return accounts;
}

You then have access to accounts[0] through accounts[20].

mjc
3,4363 gold badges38 silver badges47 bronze badges
answered Jul 11, 2011 at 1:58
Sign up to request clarification or add additional context in comments.

2 Comments

idea is to create variables with the strings we have... e.g., I have array var arr = ['myOwnName']; and from this create a variable called , var myOwnName;
You cannot create dynamically new variables, but you might consider using a Map for this purpose
27

The only way I know how to do this would be to use the JavaScript eval function.

Something like eval("account" + 1 + "='some value'");

http://www.w3schools.com/jsref/jsref_eval.asp

However, I think @Domenic has a better answer.

BuZZ-dEE
7,18316 gold badges75 silver badges105 bronze badges
answered Jul 11, 2011 at 2:00

1 Comment

His answer only is good if you know what variables you will need.
12

I was unsure about answering an old question however I stumbled across this while seeking an answer myself.

for (var i = 1; i < 11; i++) { // Creating 10 objects
window["Object"+i] = new Object();
}
console.log(Object7); // is not undefined

The above code loops to 10 while creating dynamic objects, as described on https://www.codecademy.com/en/forum_questions/51068e93f73ad4947a005629

answered Jun 27, 2017 at 14:30

2 Comments

Absolutely much better than eval() recommandation above. Thanks!
absolutely not better, node.js doesn't know what window is. Question is about js, nowhere is specified that this only should work in a browser
8

I find this a simplest solution

for (var i = 0; i < 10; i++) {
 this["RONAK"+i] = "MY VAL";
}

Output

RONAK0 = "MY VAL"
RONAK1 = "MY VAL"
RONAK2 = "MY VAL"
...
RONAK9 = "MY VAL"
answered Feb 25, 2021 at 6:09

Comments

2

You can use the eval() method to declare dynamic variables as it executes JavaScript statements passed to it.

function createVariables()
{
 for ( i=0; i<=20; i++ )
 {
 var str ="account"+ i+" = undefined";
 //Declaring and Setting dynamic variable to undefined using eval
 eval(str);
 }
}
createVariables();
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered Apr 20, 2018 at 14:44

Comments

1
let etc = { name: 'foobar', city: 'xyz', company: 'companyName' };
Object.keys(etc).forEach(key=>{
window[`${key.toUpperCase()}`] = new Object(`${etc[`${key}`]}`)
});
console.log("-->"+NAME) //foobar

this is similar to what @whatevermike describes but it does not work in NodeJS because it uses window. :(

answered Mar 27, 2018 at 20:19

Comments

0
function createVariables() {
 var accounts = [];
 for (var i = 0; i <= 20; ++i) {
 accounts[i] = "merhaba" + i;
 }
 return accounts;
}
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered Oct 13, 2016 at 14:07

1 Comment

It would be helpful to add an explanation along with your code, so that OP and others can better understand it.
0

The following code will actually create variables, instead of creating this sort of hash table proposed by @Domenic

 function createVariables(){
 var varName = "accounts";
 for (var i = 0; i <= 20; ++i) {
 eval('var ' + varName + i + ' = ' + '"whatever"' + ';');
 }
 return accounts;
 }
answered Sep 22, 2020 at 13:03

Comments

0

I was pretty proud of the way I made iterating variables with my code, was going to share it but I think I'll just sort of show you modified version of it.

function variableBuilder() {
 let i = 0;
 while (i <= 20) {
 let accountVariable = "account".concat(i);
 `// variable can even be reassigned here`
 console.log(accountVariable);
 i++;
 }
}

you can use the variable as an iterating variable identifier, in the spot that I suggested; I used this method to build DOM nodes, to create a dynamically built HTML table.

Comments

0

we can use map for it.

var map = {};
for (var i = 0; i < 10; ++i) {
 map["nutrient" + i] = "some stuff" + i;
}
console.log(map)

result:

{
 nutrient0: 'some stuff0',
 nutrient1: 'some stuff1',
 nutrient2: 'some stuff2',
 nutrient3: 'some stuff3',
 nutrient4: 'some stuff4',
 nutrient5: 'some stuff5',
 nutrient6: 'some stuff6',
 nutrient7: 'some stuff7',
 nutrient8: 'some stuff8',
 nutrient9: 'some stuff9'
}
answered Feb 22, 2022 at 20:38

Comments

0

the easiest method is to use eval and write the variable declaration line inside a loop that follows your conditions

 for (let i = 0; i <= 3; i++) {
 eval(`var variable${i}=${i}`);
 eval(`console.log(variable${i})`)
 }
//Output:
0
1
2
3

You can also console log the values outside as they are declared global with the var keyword

answered Jan 9, 2023 at 18:20

Comments

0

ES6 Method

const dyVars = 7;
for (let i = 0; i < dyVars; i++){
 eval(`var dynamicVar${i+1} = '${i+1} variable created';`);
 console.log(eval(`dynamicVar${i+1}`));
}
answered Jun 6, 2024 at 19:21

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.