Code Creating Variables

Can you write code that declares variables itself?
For example, writing code to create as many variables as there are elements in an array (which are named relative to their index number)?

Hi @net4532673862
I don’t think that the above is possible exactly as you describe it.
Probably you know destructuring? You could create a variable for each item in the array named with numbers, but that would not spare you the work of typing:

const array = ['abc', 'def', 'ghi'];

const [item1, item2, item3] = array;
console.log(item1); // "abc"

Note that variable names should not start with a number.

Maybe a little workaround would help you as it would spare you the work of typing each variable manually. You could store each item of the array in an object dynamically and name the key accordingly:

const array = ['abc', 'def', 'ghi'];
const obj = {}
array.forEach((item, index) => obj[`item${index}`] = item );

console.log(obj.item0, obj.item1, obj.item2); // "abc", "def", "ghi"
1 Like