Reputation: 41909
I just read this excellent question and top answer on "== versus ===".
var x = undefined;
When checking if x
is truly equal to undefined
, both of the below worked.
if(typeof x == "undefined") {
console.log("typeof x == \"undefined\"");
}
if(x === undefined) {
console.log("x === undefined");
}
output:
typeof x == "undefined"
x === undefined
Is one way more idiomatic than the other? If so, why?
Upvotes: 1
Views: 107
Reputation: 12961
if you use raw javascript you'd better do typeof x == "undefined"
, why?
because undefined
is a global variable which, in some browsers is not read-only and anyone could override it, for instance, in Chrome 14, or Firefox 6 you can do:
window.undefined = "MyUndefined"
and this would override the undefined
global variable, of course it seems so ridicules to do this or even to worry about this, but it is much more safer when you check your variables being undefined, like this:
typeof x == "undefined"
undefined
property.and what this has anything to do with using raw javascript:
if you use jQuery, jQuery has overrided the global variable undefined
with a real undefined
value.
Upvotes: 0
Reputation: 38183
I would say if you have control over the the range of possible values of x
then checking for x === undefined
is the most idiomatic way. For instance, if you have a function that is returning a result, or undefined
if it encounters an error.
Otherwise, you should use typeof x == 'undefined'
.
The caveat is that some expressions and variables can be undefined
because they are simply not defined, while others are explicitly defined as undefined
.
If you try to do this:
var x = undefined;
if(typeof x == "undefined") // This works
if(x === undefined) // This works
if(typeof y == "undefined") // This works
if(y === undefined) // This does not work and throws a ReferenceError
So basically, using typeof
is safer and easier if you don't have control over the variable's range because you don't have to implement exception handling.
Upvotes: 3
Reputation: 10754
Both the above conditional checks work, and therefore, can be used interchangeably. However, since you have asked about being idiomatic, I would say the conditional check: typeof x == undefined
sounds better when reading and explains what the code really does, and hence, has my personal vote :)
Upvotes: 0