DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Updated on

What does (a == null) mean in JavaScript

When we see some code from a company, such as from Google or from the ECMA committee: a == null, what does it mean?

It may seem it is for checking whether the variable refers to the primitive null, but in fact, it means:

a === null || a === undefined
Enter fullscreen mode Exit fullscreen mode

In fact, we can see that a == null is identical to using (a === null || a === undefined), not more, not less. They are exactly the same.

This is used by the ECMA TC39 (Ecma International, Technical Committee 39), when they defined optional chaining:

a?.b
Enter fullscreen mode Exit fullscreen mode

which they used

(a == null) ? undefined : a.b
Enter fullscreen mode Exit fullscreen mode

the part a == null is exactly: when a is null or undefined, then simply return undefined. This usage may be a little bit hard to understand, and is used by people more familiar with JavaScript, to "test for nullish values" — either null or undefined. While we may not use it if other people reading our code may get confused, it is good when we read a == null and know what it means.

The term "nullish" is also being used in the JavaScript community, as in nullish coalescing. We can read more about it on MDN.

Often this is all we need to know, but if we get into one technical detail:

The only exception to the rule above is document.all:

document.all == null  // true
Enter fullscreen mode Exit fullscreen mode

by the rule above, it may appear then

document.all === null || document.all === undefined
Enter fullscreen mode Exit fullscreen mode

returns true. But it returns false. This is the only known exception, but document.all returns an object, while !!document.all returns false, so document.all has very special behavior inside of JavaScript.

Reference on MDN.

Top comments (0)