The nullish coalescing operator

Learn about how to use the nullish coalescing operator in JavaScript to fall back to a default value when dealing with null or undefined.
March 24, 2021JavaScript
1 min read

The nullish coalescing operator ?? is a logical operator that allows you to fall back to a default value when dealing with null or undefined. It returns the right-hand side operand when the left-hand side operand is null or undefined. Otherwise, it returns the left-hand side operand.

The nullish coalescing operator ?? is available in TypeScript as of version 3.7.

Nullish coalescing example

const value = user.value ?? 0;

This expression is equivalent to:

const value = user.value !== null && user.value !== undefined ? user.value : 0;

When using a default value

The nullish coalescing ?? operator is recommended over || when using a default value. Consider the following example.

const value = user.value || 0.5;

When user.value is set to 0, the value from this expression will be 0.5, which may not be intended. ?? avoids some unintended behavior with || where 0, NaN and "" are treated as falsy values.

New
React Ready

Learn modern React with TypeScript.

My new book, React Ready, teaches developers modern React development skills. Go from React rookie to React ready!