How can I check if a variable exist in JavaScript?

The typeof techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined.

But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error. So this should work:

var exists = true;
try {
    if (someVar)
        exists = true;
} catch(e) { exists = false; }
if (exists)
   // do something - exists only == true if someVar has been declared somewhere.

I use this function:

function exists(varname){
    try {
        var x = eval(varname);
        return true;
    } catch(e) { return false; }
}

Hope this helps.


if ('bob' in window) console.log(bob);

Keep in mind with this way, even if you declared a variable with var, that would mean it exists.

Tags:

Javascript