typeof !== "undefined" vs. != null
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
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
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
You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:
if(window.neverDefined === undefined) {
//Code works
}
Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.
On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.