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

javascript

Solution

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`.

Problem

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.

Original source