Using typeof to check if a variable is undefined is safer than comparing it against undefined. There are several reasons why:
-
You used to be able to set any value to
window.undefined, somyUndefinedVariable === undefinedcould be lying.typeof, on the other hand, is a language construct that can't be overridden. For example:window.undefined = "my string"; window.myUndefinedVariable === undefined; // `false`, in older browsersBy the way, in modern browsers,
window.undefined = "my string";doesn't do what you might expect. The statement is silently ignored (at least in Chrome 91) but returns the given string as it would when successfully setting the value of any variable. -
The non-strict equality operator returns
truewhen comparingnulltoundefined, somyNullVariable == undefinedcould be lying. For example:const myNullVariable = null; myNullVariable == undefined; // `true`, which is misleading -
Using
=== undefinedon an object property works fine, but if it's a global variable then it blows up. For example:window.myUndefinedVariable === undefined; // `true` myUndefinedVariable === undefined; // triggers a ReferenceError, saying "myUndefinedVariable is not defined".
Using typeof for each item above:
typeof window.myUndefinedVariable === "undefined"typeof myNullVariable === "object"// let's just ignore this for now 😒typeof myUndefinedVariable === "undefined"
JavaScript being JavaScript, of course there is yet another way of checking if an object has a property that you could use for the first example above: ("myUndefinedVariable" in window) === false, but let's just not, today.