27

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
  • 58,414
  • 16
  • 114
  • 157
cardflopper
  • 976
  • 2
  • 12
  • 19

7 Answers7

54

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
  • 65,762
  • 16
  • 114
  • 184
  • 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
  • @Tron mainly because you don't control someString, but you are letting it to run as though you did. It could be malicious, have coding errors, or other nightmare-inducing issues. Imagine someString were "while(1){}" or a script that sent data to a malicious server. – BobtheMagicMoose Feb 06 '23 at 10:37
36

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ó
  • 807,428
  • 183
  • 922
  • 838
  • 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
2

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

nlogax
  • 1,091
  • 6
  • 9
2

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 Fowler
  • 1,750
  • 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
  • 159,146
  • 25
  • 197
  • 199
0
eval("alert(" + someString + ");");

would work.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

eval will do that:

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

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

As demonstrated here.

Michael Haren
  • 105,752
  • 40
  • 168
  • 205