Skip to content

Nullish Coalescing in JavaScript

To provide a default value for a value that is either null or undefined, we use the OR operator. But there’s a specific operator for this now in JavaScript. It’s called Nullish Coalescing operator.

When performing property accesses, we need to provide a default value if the result of that property access is null or undefined. At present, a typical way to express this in JavaScript is by using the || operator.

You would have used this || operator a lot, I believe.

Example

var count = data.count || 1;
// even if the value is 0, the value is defined
// we will still get 1, which we do not expect.

This kind of workaround can only be used if the value is null or undefined, right?

Nullish Coalescing Operator

This can be done easily with the Nullish Coalescing Operator ?? like below. This can be combined with optional chaining to minimize the code.

var count = data.count ?? 1;
// now if count is 0 count value is 0
// if it is null or undefined we set it to 1;

It’s currently available in Chrome Canary, and in Babel.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.