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?
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable. There are some rules while declaring a JavaScript variable (also known as identifiers). Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
Variables can be used to store data in a program, such as strings, numbers, JSON objects, or boolean values. In JavaScript, there are three different variable types: var , let , and const . Each of these variables have several rules around how they should be used, and have different characteristics.
JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With