The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.
typeof variable === "undefined&
Yet another reason for using the typeof-variant: undefined
can be redefined.
undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
The result of typeof variable
cannot.
Update: note that this is not the case in ES5 there the global undefined
is a non-configurable, non-writable property:
15.1.1 Value Properties of the Global Object
[...]
15.1.1.3 undefined
The value ofundefined
is undefined (see 8.1). This property has the attributes
{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
But it still can be shadowed by a local variable:
(function() {
var undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})()
or parameter:
(function(undefined) {
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})("foo")