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:

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:

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

// set height=100, if height is null or undefined
height = height ?? 100;

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

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