How to check for undefined in JavaScript
When a variable is declared without being assigned a value its initial value is undefined
.
How do you check if a value is undefined
in JavaScript?
The short answer
In modern browsers you can safely compare the variable directly to undefined
:
if (name === undefined) {...}
Some people argue against comparing with undefined
because old browsers allowed its value to be re-assigned like this:
undefined = "test"
After that re-assignment, comparing with undefined
directly would no longer correctly detect whether a variable was assigned a value.
However, this behavior was fixed in 2009 with ECMAScript 5:
15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
In modern browsers it's no longer possible to re-assign the global undefined
value.
What if I need to support IE8 and older?
Generally, comparing directly to undefined is still safe. There's no practical reason for an application to re-assign the value of undefined
.
Thomas Eding demonstrates this with an convincing analogy:
I don't hear people telling me that I shouldn't use setTimeout because someone can
window.setTimeout = function () { alert("Got you now!"); };
Bottom line, the "it can be redefined" argument to not use a raw
===
undefined is bogus.
If you are still concerned, there are two ways to check if a value is undefined even if the global undefined
has been overwritten.
You can use the void operator to obtain the value of undefined
. This will work even if the global window.undefined
value has been over-written:
if (name === void(0)) {...}
The zero in this example doesn't have any special meaning, you could just as well use 1
or function(){}
. void(anything)
will always evaluate to undefined
.
Alternatively, you can use the typeof operator to safely check if a value was assigned. Instead of comparing to the global undefined
value you check if the value's type is "undefined":
if (typeof name === "undefined") {...}
Note that this is slightly different from the previous options. Even if name
wasn't declared typeof
would still say it's undefined. If you compared an undeclared variable to undefined
or void(0)
you would instead get a ReferenceError.
But don't use void(0) directly
Avoid using void(0)
or typeof x === "undefined"
verbatim in code. These expressions aren't self-explanatory and should be wrapped in an isUndefined function like this:
function isUndefined(value){
// Obtain `undefined` value that's
// guaranteed to not have been re-assigned
var undefined = void(0);
return value === undefined;
}
Many utility libraries already have this functionality built in, for example there's an _.isUndefined
function in Underscore.js.