How to check for undefined in JavaScript
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.
Read full article from How to check for undefined in JavaScript
No comments:
Post a Comment