I am not asking if the variable is undefined or if it is null
. I want to check if the variable exists or not. Is this possible?
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.
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.