Reputation: 4622
I've never understood the difference in these two ways for testing the existence of an object...
typeof obj == "undefined"
vs.
obj == undefined
Is one preferred? I'm almost always using jQuery, is the second a jQuery only feature?
Upvotes: 1
Views: 208
Reputation: 185933
The problem with
obj === undefined
is that if the 'obj'
identifier name doesn't exist in the (lexical) environment (or any of the outer environments), an error is thrown (which in turn breaks your program).
Btw names are bound to the environment by either declaring a variable (var x;
), or assigning properties to the window
object (window.x = ...;
).
On the other hand
typeof obj === 'undefined'
doesn't throw (an error), and is therefore the preferred method.
Note though that you can't check for object existence in JavaScript. JavaScript code doesn't deal with objects directly, but trough references. If a given reference doesn't point to an object that doesn't mean that the object doesn't exist (it may be referenced by a different reference). What you can do is check whether or not a reference (like obj
in your case) points to an Object value (or whether or not such an identifier name exists in the first place).
So if
typeof obj === 'undefined'
evaluates to true
, that can mean:
'obj'
doesn't exist in the lexical environment or any outer environments,'obj'
exists in the lexical environment chain (it's somewhere in it) and it's bound to the undefined
value.Upvotes: 4
Reputation: 349012
undefined
can be overwritten by an arbitrary value. When comparing using ==
, null
will also return true, if undefined
is undefined
.
typeof obj == "undefined"
is a safe way to test whether an object is undefined.
The following statements are equivalent:
var obj;
typeof obj == "undefined"; // Safe
obj === undefined; // Provided that undefined has not been overwritten
obj === void 0; // Void returns an `undefined` value. Also safe
The following comparisons don't produce the desired result:
var obj = null;
obj == undefined; // True
var undefined = null; // Overwriting undefined
obj === undefined; // true
About jQuery: The self-invoking function accepts two formal parameters, while only one is given. As a result, the second parameter effectively holds the undefined
value. Now, the second parameter is also called undefined
, so inside the function, the following is true: typeof undefined == "undefined"
.
(function(window, undefined){
...
})(window)
Upvotes: 3