1

Noob question here :) Is there any way to access the value of a variable name refereed dynamically in javascript ?

What I tried :

var var1 = "foo";
var var2 = "bar";
var i = 1;
i++; 

console.log(`var${i}`);  // give me "var2"
console.log(typeof `var${i}`); // == srting` 

I want to access the value "foo" or "bar" but i'm missing something as I get only the name of the variable ?

My first question on stack, so if it's not perfect let me know I will add details, thank you !

  • 1
    I do not think you can do this. But if your values are so related that you are naming variables after them and appending a number, why not user an array and store the values in the array and access them by index? `var valueArray = ["foo", "bar"]; var i = 0; i++; console.log(valueArray[i]);` – Ken Apr 24 '17 at 22:39
  • `var var1 = "hello"; \`${eval("var" + 1)}\`` would "work" (or `window["var" + 1]` for global variables) - this is basically just another way of asking: "How can I get the value of a variable by name?" hiding inside an interpolation, which is answered elsewhere. Note that the content of `\`..\`` is *treated as an expression*. I recommend using a proper collection instead of such .. specialness. – user2864740 Apr 24 '17 at 22:45
  • ie. see http://stackoverflow.com/questions/4399794/access-value-of-javascript-variable-by-name and similar – user2864740 Apr 24 '17 at 22:48
  • `this['var' + i]` should get what you want no matter which scope your are in – Frederik.L Apr 24 '17 at 23:34
  • @Frederik.L `this[..]` will only work for *properties* on "this", including *global variables* when outside of any function. – user2864740 Apr 25 '17 at 01:02
  • 1
    @user2864740 Thanks for clarifying. Yes, I meant that it will work for variables defined in the current context. – Frederik.L Apr 25 '17 at 04:26

2 Answers2

3

If your variables are defined in the global scope, they are properties of the window object.

var var1 = "foo";
var var2 = "bar";
var i = 1;
i++; 

console.log(window[`var${i}`]);

Probably a better approach is to create a data object and store variables as properties of that.

var data = {};
data.var1 = "foo";
data.var2 = "bar";

var i = 1;
i++; 

console.log(data[`var${i}`]);
JstnPwll
  • 8,585
  • 2
  • 33
  • 56
0

You can use eval to execute dynamic code.

var var1 = "foo";
var var2 = "bar";
var i = 1;
i++; 

console.log(eval('(var' + i + ')'));  // give me "var2"
console.log(eval('(typeof(var' + i + '))')); // == srting` 
Sharada Gururaj
  • 13,471
  • 1
  • 22
  • 50