Nullish coalescing operator

Nullish coalescing operator

Modern JavaScript Series

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.