make object string javascript code example

Example: how to make string refer to object in javascript

// if variable is in global scope use: window || this
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

// if variable is in local scope use: eval
function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}