Javascript – typeof !== “undefined” vs. != null

coding-stylejavascript

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.

My question is:
How is that code any better than 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.

Why is this considered bad style?

Best Answer

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