Skip to main content

Command Palette

Search for a command to run...

Nullish coalescing operator

Modern JavaScript Series

Published
Nullish coalescing operator
C

I'm a data analyst, currently living in Copenhagen.

The nullish coalescing operator ('??') is a handy way to define a default value in case the value you are checking is nullish. A value is nullish if it's either null or undefined. Here's an example of how you would use the nullish coalescing operator:

let user = undefined;
console.log(user ?? 'Anonymous') // 'Anonymous'

If the user variable had been set to 'Jane Smith', the example above would say 'Jane Smith' instead of 'Anonymous':

let user = 'Jane Smith';
console.log(user ?? 'Anonymous') // 'Jane Smith'

So the ?? operator basically returns the first value if it's not null or undefined. But if the first value is null or undefined, it will return the second (right-hand) value.

"Now isn't this what || does?" you might say. Close, but not quite. The logical OR operator || also includes falsy values like 0. Since 0 might be a perfectly valid value to input, using the || operator would lead to bugs since we don't want to use default on a valid number. Using the ?? operator would fix that since it would return the 0 instead of a default value.

Modern JavaScript

Part 5 of 5

In this series I will go through some of the new features of JavaScript ES6.

Start from the beginning

Closures

Modern JavaScript Series