Nullish coalescing operator: ‘??’

This is a recent addition to the language. Old browsers may need polyfills.

An expression is defined when it’s neither null nor undefined. The nullish coalescing operator is written as two question marks ??. The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.

We can rewrite result = a ?? b using the operators that we already know, like this:

The common use case for ?? is to provide a default value for a potentially undefined variable.

Nullish coalescing operator ?? was added to JavaScript only recently.

The important difference between them is that:

  • || returns the first truthy value.
  • ?? returns the first defined value.

In other words, || doesn’t distinguish between false, 0, an empty string "" and null/undefined. They are all the same – falsy values.

For example, consider this:

If the zero height is a valid value, that shouldn’t be replaced with the default, then ?? does just the right thing.

Precedence

Nullish coalescing operator ?? is evaluated before = and ?, but after most other operations, such as +, *.

Summary

  • The nullish coalescing operator ?? provides a short way to choose the first “defined” value from a list. It’s used to assign default values to variables:
  • The operator ?? has a very low precedence, only a bit higher than ? and =, so consider adding parentheses when using it in an expression.
  • It’s forbidden to use it with || or && without explicit parentheses.

Developer with 2+ yrs of industrial experience in developing scalable web applications.