Categories
javascript variable-variables variables

“Variable” variables in JavaScript

118

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?

1

  • arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning

    Dec 6, 2018 at 0:32


172

tl;dr: Don’t use eval!

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 the those name/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]);

4

  • Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;

    Apr 30, 2019 at 15:40

  • In 2021 eval has become useless in this regard; at least in real world applications. Even if your CSP allows eval, I don’t know any production code that ain’t run through some minifier which will mess up your variable names.

    – Thomas

    Apr 22, 2021 at 6:36

  • eval is not just useless, but it has been disabled when running in strict mode. Many frameworks have the strict mode enabled by default, so I hope that we will see it disappearing 🙂

    Jun 20 at 9:35

  • @CristianTraìna: Where did you read that eval is disabled in strict mode? It’s not.

    Jun 20 at 9:42

42

If you are desperate to do this you can either try using eval():

var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);

Or using the window object:

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);

1

  • 2

    eval can’t create local variables in strict mode. An indirect call can create global variables, though.

    – Oriol

    Nov 27, 2016 at 22:41

6

To reference a variable in JavaScript with only a string, you can use

window['your_variable_name']

You can set and reference variables, and objects in variables too.

1

  • 1

    Almost always, better to namespace it into an object than attach all your variables globally on the window. Why? Scoping helps contain bugs, avoids name clashes and makes code easier to understand.

    – ggorlen

    Jul 7 at 0:05