Learn safe ways to check for null and undefined in JavaScript, using concise methods like val == null, while avoiding common pitfalls and ESLint issues.
Checking if the value is null or undefined in JavaScript (and TypeScript) can be a real headache and doing it incorrectly can lead to unexpected errors during runtime. In most strongly typed languages the value can be either null or not, however that’s unfortunately not the case in JavaScript.
In JavaScript, you will encounter null or undefined. To make life even harder, there are also double (abstract ==) and triple (strict ===) equality comparisons which combined with null/undefined confusion can be a challenge, especially for beginners.
Let’s start with a little theory, and later I’ll guide you through examples and finally show you a painless (and safe!) way to do the null checks in the code.
There are three value-comparisons in operations in JavaScript:
It compares the value of equality only. Before checking the values. it converts the types to match each other.
It doesn’t convert the types before performing the comparison, which means that it’s type-sensitive.
It checks if two values are the same. Unlike double equals, Object.is doesn't coerce either value. It differs from triple equals with the way it treats signed zeros and NaNs.
Now, let’s see the examples that explain the above.
Let’s jump into real-world examples. Very often we have to check if the value is null or undefined before we perform any further operations. The usual (and correct) way to do it is:
It’s correct, but it’s also long, so people very often shorten it to
In such a scenario, the expression will resolve to true, even though value isn’t null or undefined (which is what we probably intended to check in the first place).
So what should we do to avoid the tedious (val === null || val === undefined) check?
We can take advantage of the double-equals and the fact, that (null == undefined) is true.
Now you might ask – what about ESLint? It’s used in the modern projects and it enforces triple-equals. Here I might surprise you – ESLint’s rule eqeqeq [2], can be configured to allow double-equality null checks ("eqeqeq": ["error", "always", {"null": "ignore"}])
While checking for both undefined and null with a triple-equality check is correct, it is also long, so often developers tend to change it to !val check instead, which can lead to bugs in some scenarios. Changing it to a double-equality check makes it simpler and defers the 0 edge case scenarios.
References