Should I use (typeof (val) === 'undefined') or (val === undefined)?

This is similar to a number of other questions about SO, but not quite the same as what I can find.

What is the best approach for checking undefined value in Javascript and why?

First example:

var a;
if (typeof(a) === 'undefined'){...}

Second example:

var a;
if (a === undefined){...}

So, the first example compares the type name with the string, and the second compares the variable with the undefined object using the equality operator, which checks that the types are the same as the values.

What's better? Or are they both good to each other?

Please note that I am not asking about any difference between undefined and null, or truth or falsehood, only which of these two methods is correct and / or better.

+5
source share
3 answers

, , undefined. typeof.

> foo === undefined
ReferenceError: foo is not defined
    at repl:1:2
    at REPLServer.eval (repl.js:80:21)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)
    at ReadStream.<anonymous> (readline.js:82:12)
    at ReadStream.emit (events.js:88:20)
    at ReadStream._emitKey (tty.js:320:10)
> typeof foo === "undefined"
true

() undefined, , undefined undefined.

+9

undefined , . ,

(function(undefined){
    var a;
    if (a === undefined) {
})();
// note called without parameter, so undefined is actually an undefined value

,

: , ECMA 5 undefined, .

+1

, typeof undefined. , typeof().

ECMA 3 undefined :

undefined = "not undefined";

And this can lead to ugliness compared to undefinedlater. In ECMA 5, this is prohibited. This means that most modern browsers will not let you set the value undefined, and you should be safe with === undefined.

Also, if you are not even sure if the variable you are checking was specified, you should use it typeof, otherwise you will get a reference error.

0
source

All Articles