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
myUndefinedVariable === 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 browsers
By 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
myNullVariable == undefinedcould be lying. For example:
const myNullVariable = null; myNullVariable == undefined; // `true`, which is misleading
=== 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".
typeof for each item above:
typeof window.myUndefinedVariable === "undefined"
typeof myNullVariable === "object"// let's just ignore this for now 😒
typeof myUndefinedVariable === "undefined"
("myUndefinedVariable" in window) === false, but let's just not, today.