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?
8 Answers
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.
try this
var ex=false;
try {(ex=myvar)||(ex=true)}catch(e) {}
alert(ex);
where ex
is true if myvar
has been declared.
working example: http://jsfiddle.net/wcqLz/
I think it depends on what you want to do with the variable.
Let's say, for example, you have a JS library that will call a function if it has been defined and if not, then not. You probably know already that functions are first level objects in JS and are as such variables.
You could be tempted to ask first if it exists, and then call it. But you can just as well wrap the attempt at calling it in a try/catch block.
Example of code that calls a function, if defined, before and after firing an event:
function fireEvent(event)
{
try
{
willFireEvent(event); // Is maybe NOT defined!
} catch(e) {}
//... perform handler lookup and event handling
try
{
hasFiredEvent(event); // Might also NOT exist!
} catch(e) {}
}
So instead of checking for the variable, catch the error instead:
var x;
try
{
x = mayBeUndefinedVar;
}
catch (e)
{
x = 0;
}
Whether this is a good thing or not in terms of performance, etc., depends on what you're doing...