The JavaScript Double Question Mark: How to Use Nullish Coalescing

The JavaScript Double Question Mark: How to Use Nullish Coalescing

Written

JavaScript's double question mark (??) is also known as the nullish coalescing operator, and it's used to set a default "fallback" value in case of another value being either null or undefined.

Here's a quick example:

We can see that because initialValue was set to null, our use of the nullish coalescing operator sets processedValue to the string pizza.

And we can expect the same outcome if we were to set initialValue to undefined, but setting initialValue to any other value would not cause us to evaluate the right side of the nullish coalescing operator.

Syntax

Let`s take a closer look at the syntax of the nullish coalescing operator.

The ?? operator is used in between two values:

When it`s evaluated, the JavaScript interpreter will first see what the left side of the operator evaluates to.

And as mentioned above, we only ever evaluate the right side of the operator if the left side is null or undefined.

When to use the Nullish Coalescing Operator

The nullish coalescing operator ?? is useful anytime we want to create special logic for handling JavaScript's two empty states: undefined and null.

Some examples of times that this is helpful are

  • Processing data received from a third-party API
  • Processing user-defined form data
  • Setting reasonable defaults to avoid race conditions

And many more. You'll find that the nullish coalescing operator is helpful in nearly as many cases as its cousin, the "double pipe" (||) OR operator.

In fact, they're so similar to each other that we should take a moment to look at how they're different.

Comparison to the || OR operator

The ?? operator can be thought of as being useful in a subset of cases that the || operator can be used.

The right side of the ?? operator is only evaluated if the left side is undefined or null.

But the right side of the || is evaluated if the left side is:

  • undefined
  • null
  • ""
  • 0
  • false

In other words, the || operator is used when you want a broader "falsey" case to trigger the right side, while the ?? operator should be used if you only want a more-narrow "empty" case to trigger the right side.

Examples

Let`s take a look at how the nullish coalescing operator handles different values and how that differs from the OR operator.

Here is how null is handled with each operator:

Here is how undefined is handled with each operator:

Here is how an empty string ("") is handled with each operator:

Here is how 0 is handled by each operator:

Here is how false is handled by each operator: