Reputation: 1566
This is similar to a number of other questions on SO, but not exactly the same as any I can find.
Which is the best approach for checking for an 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 is comparing the name of the type to a string, and the second is comparing the variable to the undefined object, using the equality operator, which checks that the types are the same as well as the values.
Which is better? Or are they both as good as one another?
Note that I'm not asking about any difference between undefined and null, or truthy or falsey, just which of these two methods is correct and/or better.
Upvotes: 5
Views: 1564
Reputation: 20269
The two methods are correct, but the typeof
one is immune to changes to the value of undefined
. If you need stricter checking, use typeof()
.
In the ECMA 3 standard, you can modify the value of undefined as such:
undefined = "not undefined";
And this can lead to ugliness when comparing to undefined
later on. In ECMA 5, this is disallowed. This means most modern browsers will not let you set the value of undefined
, and you should be safe using === undefined
.
Also, if you're not even sure whether the variable you are checking has been defined, you should use typeof
, otherwise you will get a reference error.
Upvotes: 0
Reputation: 26749
The undefined
can be assigned a value, and the type check won't work. Unless the scope of the code is protected, e.g.
(function(undefined){
var a;
if (a === undefined) {
})();
// note called without parameter, so undefined is actually an undefined value
this way to check is not safe, and first one is prefered
Edit: It seems that ECMA 5 dissalows assigning value to the undefined, but still this depends on the browser implementation.
Upvotes: 1
Reputation: 944568
If a variable doesn't exist, then you'll get a reference error when you try to use it — even if you are comparing it to undefined
. So always use 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
It is also possible for (bad) code to overwrite undefined
, which would cause an undefined value to not be equal to undefined
.
Upvotes: 10