javascriptcomparison

The difference between `typeof x !== "undefined"` and `x != null`


I often see JavaScript code which checks for undefined parameters etc. this way:

if (typeof input !== "undefined") {
    // do stuff
}

This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because undefined could be renamed, though.

But there is also this approach:

if (null != input) {
    // do stuff
}

As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (e.g. for optional function parameters).

Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator.

How is using a typeof check useful beyond just checking for null != input?


Solution

  • typeof is safer as it allows the identifier to never have been declared before:

    if(typeof neverDeclared === "undefined") // no errors
    
    if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined