Just Frontend Things

The nullish coalescing operator

JavaScript

2021-01-20

Learn how to fallback to a value only if the first provided value is undefined or null, using the the nullish coalescing operator.

A normal way to use fallbacks is to use Logical OR ||:

const logicalOr = input => { return input || 'fallback'; };

The result of this function would be:

logicalOr(7); //=> 7 logicalOr(-13); //=> -13 logicalOr(0); //=> 'fallback' logicalOr(false); //=> 'fallback' logicalOr(null); //=> 'fallback' logicalOr(undefined); //=> 'fallback'

Notice how an input of 0 and false results in 'fallback':

logicalOr(7); //=> 7 logicalOr(-13); //=> -13 logicalOr(0); //=> 'fallback' logicalOr(false); //=> 'fallback' logicalOr(null); //=> 'fallback' logicalOr(undefined); //=> 'fallback'

If we instead use a nullish coalescing operator ??:

const nullishOr = input => { return input ?? 42; };

The result of this function would be:

nullishOr(7); //=> 7 nullishOr(-13); //=> -13 nullishOr(0); //=> 0 nullishOr(false); //=> false nullishOr(null); //=> 'undefined' nullishOr(undefined); //=> 'undefined'

Notice how an input of 0 and 0 results in false:

nullishOr(7); //=> 7 nullishOr(-13); //=> -13 nullishOr(0); //=> 0 nullishOr(false); //=> false nullishOr(null); //=> 'undefined' nullishOr(undefined); //=> 'undefined'

Logical OR, ||, will return the fallback if the left hand value is "falsey" like 0, false, undefined, null or empty string.
Nullish Coalescing Operator, ??, will return the fallback only if the left hand value is undefined or null.

0 || 'fallback' //=> 'fallback' 0 ?? 'fallback' //=> 0
false || 'fallback' //=> 'fallback' false ?? 'fallback' //=> false
undefined || 'fallback' //=> 'fallback' undefined ?? 'fallback' //=> 'fallback'