"Variable" variables in JavaScript
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?
Solution 1:
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 class
es.
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]);
Solution 2:
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]);
Solution 3:
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.