"Variable" variables in JavaScript

ghz 1years ago ⋅ 5276 views

Question

I know it's possible in PHP to have "variable" variables. For example,

$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"

Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?


Answer

tl;dr:[Don't use eval!](https://stackoverflow.com/questions/86513/why-is- using-the-javascript-eval-function-a-bad-idea)

There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.

There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.

If you have a fixed set of names, such as

// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));

store those names/values as properties of an object and use bracket notation to look them up dynamically:

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

In ES2015+ it's even easier to do this for existing variables using concise property notation :

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);

If you have "consecutively" numbered variables, such as

// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

then you should be using an array instead and simply use the index to access the corresponding value:

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);