Nullish coalescing operator: ‘??’

Abhay Jain
2 min readDec 30, 2020

--

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:

result = (a !== null && a !== undefined) ? a : b;

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:

let height = 0;alert(height || 100); // 100
alert(height ?? 100); // 0

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:
// set height=100, if height is null or undefined
height = height ?? 100;
  • 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.

--

--

Abhay Jain
Abhay Jain

Written by Abhay Jain

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

No responses yet