Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading