JavaScript: Is it possible to declare a variable using another variable's value?

883 Views Asked by At

Here is an example of what I'm trying to accomplish:

const a = 'name';
const ${a} = 1;

The second variable should be:

const name = 1;

Is this possible? Thank you in advance.

2

There are 2 best solutions below

0
Noble Eugene On

Could use an object though, something like

var obj;
var x = "name";
obj[x] = 1;

console.log(obj[x]);
0
Steve Hollasch On
const a = 'name';
eval (a + " = 37");

This will create a variable name with the value 37.

However, I prefer Nobel Eugene's solution as a better approach to the problem.