if (x === undefined) ...
> undefined = 123 > undefined undefinedYou can, however, shadow it in a function, either via a parameter or via a local variable:
> (function () { var undefined = 123; return undefined; }()) 123From now on, undefined is used to refer to the identifier, while undefined is used to refer to the actual value.
Because you could globally change the value of undefined under ECMAScript 3, two techniques were often used to ensure that it had the correct value. If you are targeting older browsers, these techniques are still relevant.
Technique 1: shadow undefined yourself.
(function (undefined) { if (x === undefined) ... // safe now }()); // don’t hand in a parameterAbove, undefined is a parameter whose value is undefined, because it has not been provided by the caller.
Technique 2: compare with void 0. The void operator [2] evaluates its operand, ignores the result and returns undefined. That means that void 0 will always evaluate to undefined.
if (x === void 0) // always safe
if (typeof x === 'undefined') ...This is more verbose and can be slower (though many engines optimize). It has two advantages: First, it is safe with regard to a changed undefined (not that important under ECMAScript 5). Second, it also works for unknown variables:
> typeof iDontKnowThisVariable === 'undefined' true > iDontKnowThisVariable === undefined ReferenceError: iDontKnowThisVariable is not defined
> Boolean(undefined) falseHence, you can check for undefined like this:
if (!x) ...The usual caveat applies: The condition of the above if statement will also be true for: null, false, -0, +0, NaN, "".