Javascript: interpret string as object reference? [duplicate]

If the variable is in the global scope, you can access it as a property of the global object

var a = "hello world";
var varName = "a";
console.log( window[varName] ); // outputs hello world
console.log( this[varName] ); // also works (this === window) in this case

However, if it’s a local variable, the only way is to use eval (disclaimer)

function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}

Unless you can put your dynamic variables into an object and access it like a property

function () {
  var scope = {
    a: "hello world";
  };
  var varName = "a";
  console.log( scope[varName] ); // works
}

Leave a Comment