My Work Notes

23 Dec 2022

Nullish Coalescing Operator in JavaScript

The nullish coalescing operator (??) is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.

Unlike the logical OR operator (||), the nullish coalescing operator does not return the right-hand operand if the left-hand operand is any other falsy cases such as empty string, false or 0.

That’s why the nullish coalescing operator is a more concise way of writing a typical pattern in JavaScript where you want to fall back to a default value if a variable is null or undefined in many cases.

Here is an example of how to use ‘??’ operator:

const userName = user.name ?? 'Guest';

In this example, if user.name is null or undefined, the string 'Guest' will be assigned to the userName variable. If user.name is any other value (including an empty string), that value will be assigned to userName.

The next example shows a difference between the logical OR (||) operator and the nullish coalescing operator (??).

const userName = user.name ?? 'Guest'; 
// returns 'Guest' if user.name is null or undefined
// returns user.name if it is any other value

const userName = user.name || 'Guest';
// returns 'Guest' if user.name is falsy (e.g. null, undefined, '', 0, or false)
// returns user.name if it is truthy (e.g. a non-empty string or a non-zero number)

The nullish coalescing operator is not combineble with AND (&&) and OR (||) operators in one expression. So, the following code will not work and throw a SyntaxError:

const userName = user.name ?? 'Guest' || 'Anonymous';
const userEmail = user.email ?? 'Unknown' && 'Not specified';

Instead, you can use parentheses to group the expressions:

const userName = (user.name ?? 'Guest') || 'Anonymous';
const userEmail = (user.email ?? 'Unknown') && 'Not specified';

The nullish coalescing operator is a relatively new feature in JavaScript. It appeared in ES2020. It is supported in all modern browsers and Node.js. If you want to use it in older browsers, you can use a transpiler like Babel to transpile your code to ES5.