Search code examples
javascriptjavascript-objectsevaldynamic-variables

Can you use a variable name to reference an Object without using eval()


So,

I know it is possible to create dynamic keys on an object.

const foo = 'bar';
const obj = {
    [foo]: 'this is bar',
};

But is it possible to reference objects by a variable value. For instance if we have 3 objects:

const obj1 = {}
const obj2 = {}
const obj3 = {}

And an array which holds their names

const objects = ['obj1', 'obj2', 'obj3'];

Can we loop through those names and reference their objects. This won't work:

objects.forEach(obj => Object.assign(obj, { extended: true }));

But this will:

objects.forEach(obj => Object.assign(eval(obj), { extended: true }));

But the docs at Mozilla state "Do not ever use eval!"


Solution

  • The answer is that you can't.

    In JS, there's no way to access or create variables dynamically, unless you eval (or the very similar Function constructor).

    Although the variables created in the global scope with var will become properties of the global object and you can access them on it, that's also not recommended (due to the problems arisig with var, using reserved names, etc.), and works only in the global scope (which is even worse to mess with).

    The best thing you can do is to place these variables into an object instead, and that way you can access them dynamically. JS variables aren't good for that.