typeof !== "undefined" vs. != null
typeof
is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errorsif(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
If the variable is declared (either with the var
keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof
to avoid a ReferenceError
.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){ // undefined is now what it's supposed to be})();
Or obtain it via the void
operator:
const undefined = void 0;// also safe
good way:
if(typeof neverDeclared == "undefined") //no errors
But the best looking way is to check via :
if(typeof neverDeclared === typeof undefined) //also no errors and no strings