There is no single solution to this. It is possible to dynamically accesssomeglobal variables through thewindow, but this does not apply to local variables of a function.Global variables that do notbecomewindowattributes are variables defined withletandconst, andclasses.
There is almost always a better solution than using mutable variables!Instead, you should look atdata structuresand choose the correct data structure for your problem.
If you have a fixed set of names like
// BAD - DON'T DO THIS!!! var foo = 42; var bar = 21; var key = 'foo'; console.log(eval(key));
If you desperately want to do this, you can try using eval():
Or use window object:
tl;dr:Don't use
eval
!There is no single solution to this. It is possible to dynamically access
some
global variables through thewindow, but this does not apply to local variables of a function.Global variables that do notbecomewindow
attributes are variables defined withlet
andconst
, andclasses.
There is almost always a better solution than using mutable variables!Instead, you should look atdata structuresand choose the correct data structure for your problem.
If you have a fixed set of names like