Sarah has a bug where she knows that:
typeof(foo) == 'undefined'
is true, but when she tested:
foo == undefined
it is false. How can this be? This is because undefined is not a literal in ECMAscript. Lots of people use undefined expecting it to be undefined, but it doesn’t have to be, at least not according to the spec. (null on the other hand, is a literal, defined to be the sole member of the Null type, just as the literals true and false are the only members of the Boolean type and cannot be redefined, and 1, 2, … Infinity are Number literals.)
If you try this in the debugger:
global[undefined] = 42
you will get a warning from the compiler, but now when you type:
undefined
you will find that it is indeed 42!
What’s the right way to test for undefined? It depends. Do you really need to know if a variable is undefined? If so, the typeof test is one valid way. The other valid way would be:
foo === void 0
void will cast any value to undefined — 0 is just a convenient (literal) value to use. Note the use of === to test for identical to undefined, if you really are testing for undefined, because:
null == void 0
is also true, so if you used == you would only know that foo was either null or undefined.
If all you need to know is that foo is not undefined, null, false, , or "" (an empty string), then you can use:
Boolean(foo)
or:
!!foo
or:
if (foo) { ... }
because all of undefined, null, false, and "" coerce to false in a boolean context.
The moral of the story is: Don’t assume undefined is undefined. If you really need the undefined value, use void 0, or test for typeof(...) == 'undefined'.
Thanks for signing in, . Now you can comment. (sign out)
(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)