Wednesday, 5 July 2017

javascript - typeof !== "undefined" vs. != 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.



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?


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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...