简体   繁体   中英

Checking for Undefined with `typeof ==` and `===`

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?

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.

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 :)

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"
  • this is the main reason why I'm against using the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM