Nullish coalescing in Node.js 14 and JavaScript

Published on

2 min read

The Nullish coalescing operator in useful to handle default values, without short-circuiting on values that result as falsy.

Falsy values are undefined, null, false, 0, NaN, and '' in JavaScript, and sometimes you want to retain those values, explicitly excluding null and undefined.

The best example is if you have a property that could assume the values true, false and undefined (or null).

Additionally, the property should become true (default value) if it’s not set.

You could be inclined to write something like this:

const trialActive = user.trialActive || true

But what happens if the user has the property set to false? The operator || will use the right-hand side of the expression, and set the variable trialActive to true!

That’s not what we want. Only if the trialActive property is unset (e.g. null or undefined), the value should be assigned to true, not otherwise.

Here’s where the Nullish coalescing operator comes in handy.

const trialActive = user.trialActive ?? true

In this case, only if the trialActive property is set to undefined or null, the default value true is used.

In the other cases, when user.trialActive contains the value true or false, the actual value is used, without short-circuiting the expression.

If you’re interested, here is a blog post that describes Optional chaining in more detail.

For more in-depth explanation, I strongly suggest to skim through this blog post on where Nullish coalescing is discussed way more in depth.

Portions of this page are modifications based on work created and shared by the V8 project and used according to terms described in the Creative Commons 3.0 Attribution License.