Using typeof to check if a variable is undefined is safer than comparing it against undefined. There are several reasons why:

  1. You used to be able to set any value to window.undefined, so myUndefinedVariable === undefined could 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.

  2. The non-strict equality operator returns true when comparing null to undefined, so myNullVariable == undefined could be lying. For example:

    const myNullVariable = null;
    myNullVariable == undefined; // `true`, which is misleading
    
  3. Using === undefined on 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:

  1. typeof window.myUndefinedVariable === "undefined"
  2. typeof myNullVariable === "object" // let's just ignore this for now 😒
  3. typeof myUndefinedVariable === "undefined"
Final thoughts

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.

Previous on JavaScript
Mastodon Mastodon