42

Is there a way to find JavaScript variable on the page (get it as an object) by its name? Variable name is available as a string constant.

1

7 Answers 7

36
<script>
var a ="test";
alert(a);
alert(window["a"]);
alert(eval("a"));
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Please don’t use eval for this.
What about non-global variables? Is there any other option but eval?
@mxro: In that situation, you'd want to use an object property.
31

All JS objects (which variables are) are available within their scope as named properties of their parent object. Where no explicit parent exists, it is implicitly the window object.

i.e.:

var x = 'abc';
alert(window['x']); //displays 'abc'

and for a complex object:

var x = {y:'abc'};
alert(x['y']); //displays 'abc'

and this can be chained:

var x = {y:'abc'};
alert(window['x']['y']); //displays 'abc'

5 Comments

that's only true for globally scoped variables - if the scope is function-level, there's no object which allows access to the lexical environment
Sure, but nothing helps you there. This assumes you can express the var as a dot notation construct.
If you need to do it within a function, the only solution is to put your vars in an objection, and access the object's keys, like this example: stackoverflow.com/questions/4109297/…
@Juan - that wouldn't be function level scope though.
that's the point of my comment. You can't do it to local functions without eval.
6

If you are wanting a variable that is declared in the global context, it is attached to the window object. ex: window["variableName"]. All variables are a hash table value within their scope.

If you have to use dotted notation, then you will want to follow kennebec's suggestion, to navigate through the object hierarchy. eval() can work as well, but is a more expensive operation than is probably needed.

Comments

5

If it's a global variable, you can look it up by name on the global object, since global variables are properties of the global object. On browsers, there's a global variable that refers to the global object called window, so:

var name = "foo";
window.foo = 42;
alert(Number(window[name])); // 42

But global variables are a Bad Thing(tm).

To do this without globals, use your own object:

var name = "foo";
var obj = {};
obj.foo = 42;
alert(Number(obj[name])); // 42

Both of the above work because in JavaScript, you can refer to an object property either with dot notation and a literal (obj.foo), or with bracketed notation and a string (obj["foo"]), and in the latter case, the string can be the result of any expression, including a variable lookup.

5 Comments

What about if obj would be the variable to be accessed (and not obj.foo) - would eval be the only option then?
@mxro: If obj were a global, you could use window["obj"]. If it weren't, then you'd have to use eval. But I wouldn't, I'd change my code to put obj in a container so I could just look it up in the normal way.
Yes, that sounds good. I think I initially created a variable in an eval statement, which then I could retrieve only through a second eval - but then changed the code that a container variable is created before the first eval; eliminating the need for the second eval.
@mxro: If you create a variable in an eval, you should be able to access it normally: eval("var x = 42;"); console.log(x); shows 42 in the console. (But there's almost never any reason to use eval.)
Wow, thanks, that's also useful. But you are right, not very clean, I agree!
4

If your string references a 'deep' property of a global, like 'Yankee.console.format' you can step through the references:

String.prototype.deref= function(){
    // remove leading and trailing quotes and spaces
    var obj= this.replace(/(^[' "]+|[" ']+$)/g,'');

    var M= obj.match(/(^[\w\$]+(\.[\w\$]+)*)/);
    if(M){
        M= M[1].split('.');
        obj= window[M.shift()];
        while(obj && M.length) obj= obj[M.shift()];
    }   
    return obj || this;
}

Comments

4
var getVar = function (obj) {
    for(var key in this) {
        if(obj === this[key]) return key;
    }
};

foo = 'foo';

console.log( getVar(foo) ); // => 'foo'

https://stackoverflow.com/a/17432007/1250044

2 Comments

double foo do helps to follow
This will merely return the value of the first variable on the window that has the given value. I don't see the point in doing this as it won't tell you anything you don't already know.
2

You could use eval()

8 Comments

never ever use eval where you don't have to
vote up. simple question deserves a simple answer. i'd go with eval() if I for whatever reason needed to look at the contents of a variable by its name.
A). what's not simple about window[foo]? B). speed and security don't concern you then? eval is toxic, seriously
I'd hate for anyone to think this was a competition - I really honestly don't downvote for that - and I accept that eval does technically solve the problem, but nonetheless eval is the nuclear option. It's better if you don't have to use it.
@Peter, it's not a competition, but most well versed JS developers avoid eval and with like the plague. It should be OK to express dislike towards your solution. I would never post eval as a solution, unless there was no other, or it was just too cumbersome
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.