Search code examples
javascriptarraysvariablesecmascript-6template-literals

How can I construct a variable in JavaScript based on another variables value? And How can I reassign it's value and perform methods on that variable?


I want to be able to basically do this

let x = 1;
let `arr${x}`;

if ((i = 0)) `arr${x}` = [];
`arr${x}`.push(words);
console.log(`arr${x}`);

I have tried using eval()

let x = 1;
eval(`let arr${x}`);

if ((i = 0)) eval(`arr${x} = [];`);
eval(`arr${x}.push(${words})`);
console.log(eval(`arr${x}`));

But it's giving an error: Uncaught ReferenceError: arr1 is not defined In this line: eval(arr${x}.push(${words}));


Solution

  • You can't do this with variables, but you can very well do it with object properties. If the object you create it on happens to be the global object (window in browsers) this will also create a global variable:

    let x = 1, words = "some words here", i = 0;
    window[`arr${x}`] = undefined;
    
    if (i===0) window[`arr${x}`] = [];
    window[`arr${x}`].push(words);
    console.log(window[`arr${x}`]);
    console.log(arr1);