How can you use dynamic variable names in JavaScript?

How can you use dynamic variable names in JavaScript?

In PHP, you can do things like this:

$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name; // prints 1

Is there a way to achieve something similar in JavaScript? For example, if I have a variable var name = ‘variableName’;, can I get a reference to the variable with the name stored in name using a javascript dynamic variable name approach?

Hi,

JavaScript doesn’t support dynamic variable names directly, but you can use an object to store key-value pairs.

Each key can act as a variable name:

var variables = {
a: 1,
b: 2,
c: 3
};
var name = 'a';
console.log(variables[name]); // prints 1