Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to check if variable exists by variable name?

Tags:

javascript

I am having this issue. I have a script that checks if variable exists, because some scripts load asyncronously, like FB for Facebook or twttr for Twitter.

function whenAvailable(name, callback, interval) {
    interval || (interval = 100); // ms
    window.setTimeout(function() {
        if ((window.hasOwnProperty && window.hasOwnProperty(name)) || window[name] || !!eval(name)) {
            return callback();
        } else {
            window.setTimeout(arguments.callee, interval);
        }
    }, interval);
}

Looks like this

if ((window.hasOwnProperty && window.hasOwnProperty(name)) || window[name] || !!eval(name)) 

does not work. IE throws error for eval(name) -- e.g. if name = 'FB', it says it can't eval 'FB' which is undefined.

window.hasOwnProperty(name) does not work if name == 'twttr.widgets'.

Is there a universal and cross browser check for existence of var by var name?

like image 668
mvbl fst Avatar asked Mar 29 '12 15:03

mvbl fst


2 Answers

First off, you don't need that eval (you almost never do), you can index into a JavaScript object using a string and bracketed notation, e.g.:

window['FB'];

or

name = 'FB';
foo = window[name];

So to check:

if (typeof window[name] === "undefined")

...except that doesn't differentiate between the property not existing at all, or existing but having the value undefined.

or

if (name in window)

...but that checks the prototype as well as the object. It's fine for window, though.

window.hasOwnProperty(name) does not work if name == 'twttr.widgets'.

Right, you have to break it up:

var index = 0,
    parts = name.split('.'), // doesn't handle [] notation
    result;
result = window;
index = 0;
try {
    while (typeof result !== "undefined" && result !== null && index < parts.length) {
        result = result[parts[index++]];
    }
}
catch (e) {
}
if (index < parts.length) {
    // Didn't find all of it
}

...or something to that effect.

like image 168
T.J. Crowder Avatar answered Sep 30 '22 00:09

T.J. Crowder


I've always just used things like:

if (window[name]) {
    return 'it exists';
} else {
    return 'nope';
}

EDIT: This works because if window[name] isn't there, the if determines undefined to be false.

like image 28
kiswa Avatar answered Sep 30 '22 00:09

kiswa