1
const var1 = "Some Value"
const var2 = "Another value"

const var3 = "var1"

Then how can we access the variable var1 by using var3? var3 has a value var1 and there's a variable exists with var1, so this should return "Some Value" instead of "var1"

Ravi.K
  • 41
  • 1
  • 6

3 Answers3

3

If you have the name of a variable as a string, you can access it by key on the window.

var var1 = "abc";
var var2 = "var1";

console.log(window[var2]);

In Node.js, you would use the global keyword instead.

console.log(global[var2]);
Liftoff
  • 24,717
  • 13
  • 66
  • 119
2

You can use eval()

const var1 = "Some Value"
const var2 = "Another value"
const var3 = "var1"

console.log(eval(var3))
axtck
  • 3,707
  • 2
  • 10
  • 26
-1

It would be better if you create an object dynamically and try to access using bracket notation. you won't need var. It will work with let and const as well.

console.log({var1:var1,var2:var2,var3:var3}[var3])

In latest es you can also do something like

console.log({var1,var2,var3}[var3])
diwakersurya
  • 94
  • 1
  • 6