1

I need to create dynamically name of variable with a loop .

example:

const1 = test;

const2 = test;

const3 = test; ....

I try this , but that only create 20 same variable name in array

I need a unique name increment by 1 at each loop and return each variable to use after.

function createVariables(){
  var accounts = [];

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

  return accounts;
}

how can I do this ?

4
  • 5
    The code you posted looks like a fine solution. Generally when you find yourself wanting to name variables with names like that, you really want an array. That's what arrays are for. Commented Jun 11, 2020 at 16:48
  • 1
    This sounds like a textbook xy problem, what exactly do need this for? Commented Jun 11, 2020 at 16:49
  • 3
    Making that many variables really does not make any sense and is not easy maintainable. Using an array is a better approach. What is using the variables? Commented Jun 11, 2020 at 16:51
  • does the function trigger on a button click? Commented Jun 11, 2020 at 16:51

3 Answers 3

2

Using Object could be the work around

var accounts = {};

  for (var i = 0; i <= 20; ++i) {
      accounts["const"+i] = "test";
  }
  
  console.log(accounts)

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

Comments

0

If you need variable (not array), then you can use this code:

for (let i = 0; i <= 20; ++i) {
  window[`whatever${i}`] = + i; 
}

console.log(whatever0)
console.log(whatever1)
//...
console.log(whatever19)

See in playground: https://jsfiddle.net/denisstukalov/thvc2ew8/4/

Comments

0

What is it that you are trying to achieve? As mentioned in some of the comments, and array would be a better approach.

That said, one solution is to set values on a JavaScript object using string indexer (['']). See example below:

function createVariables(obj){
  for (var i = 0; i <= 20; ++i) {
    obj[`const${i}`] = "whatever";
  }
}

// add it to a new object
const accounts = {};
createVariables(accounts);
console.log(accounts.const1, accounts.const2, accounts.const3);

// avoid adding it to global scope (like window)
createVariables(window);
console.log(const1, const2, const3);

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.