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?
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 ofwindoware variables defined withletandconst, andclasses.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
store those names/values as properties of an object and use bracket notation to look them up dynamically:
In ES2015+ it's even easier to do this for existing variables using concise property notation:
If you have "consecutively" numbered variables, such as
then you should be using an array instead and simply use the index to access the corresponding value: