Search code examples
javascriptvariable-variables

Variable variables in JavaScript


according to my knowledge, this feature already exists in PHP. lets look at the following php code:

$color = 'red';
$$color = 'dark';

description of the feature:

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, red, can be used as the name of a variable.At this point two variables have been defined and stored in the PHP symbol tree: $color with contents "red" and $red with contents "dark".

my Question

can this be done in java Script?


Solution

  • var color = 'red';
    window[color] = 'dark';
    console.log(color, red);