26

Is there a way to refer to a Javascript variable with a string that contains its name?

example:

var myText = 'hello world!';
var someString = 'myText';

//how to output myText value using someString?
isherwood
  • 52,576
  • 15
  • 105
  • 143
cardflopper
  • 916
  • 2
  • 12
  • 19

7 Answers7

52

You can use an eval to do it, though I try to avoid that sort of thing at all costs.

alert(eval(someString));

A better way, if you find yourself needing to do this, is to use a hash table.

var stuff = { myText: 'hello world!' };
var someString = 'myText';
alert( stuff[someString] );
friedo
  • 64,458
  • 16
  • 112
  • 180
  • 1
    if I'd rather use the window['varname']; approach, how would I do it using with an object? `var obj = {'eleID':'varname'}; for (var key in obj) { window[obj[key]]; }` This doesn't seem to work :( – CJT3 Jun 21 '14 at 03:41
  • 4
    I keep seeing people saying to avoid using eval for this and similar questions - but why? – Tron Mar 27 '18 at 17:31
34

If that variable is on the global scope, you can use the bracket notation on the global object:

var myText = 'hello world!';
var someString = 'myText';

alert(window[someString]);
Christian C. Salvadó
  • 769,263
  • 179
  • 909
  • 832
  • 4
    Amazing answer saves the use of eval +1 wish i could + 10 – Lemex Aug 28 '12 at 14:02
  • So goOD! Thank you! This is what I was looking for! `eval()` worked for my main case, but I couldn't check if the variable I was using `eval()` to exercise was defined or not. `typeof window[event.data.lingua_target_content_var] !== 'undefined'` works when `eval()` threw an error! – jerclarke Mar 05 '19 at 20:20
1

Assuming this is at the top level, window[someString] === "hello world!".

nlogax
  • 1,081
  • 6
  • 9
1

In JavaScript, there is no standard for creating a 'Master Object', or any built-in method to access variables on the initial scope with a string reference that I am aware of.

However, if you are using JavaScript for web development on a browser, the window Object will give you complete access to your current scope. For example:

myVar = "This is my var"; 
if(myVar == window.myVar){
     /*
         This statement would return true
         Because both variables reference
         the same string;
     */
}

This method will allow you to reference any scope-variable WITHOUT making it a string, but you can also use a string as needed with the bracket ([]) Selectors.

window['myVar']

It is worth mentioning that keeping data as a variable directly on the current scope leaves it open to be re-defined by other scripts running. Your variable can be overwritten by function argument names, for loop variables, and simply by assigning a new value to that variable.

To overcome this, I suggest using an Object to store all relevant data to your application (Static And/Or OOP). Like this:

$myApp = {
     var1 : 'This is Var1',
     apply : function(){
          alert('Started!');
     }
}

//Referencing relative variables
alert($myApp.var1);
Adam F
  • 1,742
  • 1
  • 17
  • 18
0

You can do this with eval:

var myText = 'hello world!';
var someString = 'myText';

eval('var theTextInMyText = ' + someString + ';');

alert(theTextInMyText);

The desire to do this at all usually is a "code smell". Perhaps there is a more elegant way...

Asaph
  • 154,284
  • 25
  • 189
  • 193
0
eval("alert(" + someString + ");");

would work.

Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
0

eval will do that:

var myText = 'hello world!!';
var someString = eval('myText');

document.getElementById('hello').innerHTML = someString;

As demonstrated here.

Michael Haren
  • 101,522
  • 39
  • 162
  • 203