Skip to content

Nullish Coalescing Operator

The nullish coalescing operator ?? supplies a default for a missing value. a ?? b gives a unless a is null or undefined, the two nullish values, in which case it gives b. It arrived in ES2020 and works in every current browser and in Node.js 14 and later.

|| also supplies defaults, but it replaces every falsy value, including 0, false and the empty string. ?? replaces only null and undefined, so it keeps those values when they are real settings:

const settings = { volume: 0, nickname: '', theme: null };
console.log([settings.volume || 50, settings.volume ?? 50]);
console.log([settings.nickname || 'Guest', settings.nickname ?? 'Guest']);
console.log([settings.theme || 'light', settings.theme ?? 'light']);
console.log([settings.fontSize || 16, settings.fontSize ?? 16]);

This prints:

[ 50, 0 ]
[ 'Guest', '' ]
[ 'light', 'light' ]
[ 16, 16 ]

Each line shows the || result first and the ?? result second. For theme, which is null, and fontSize, which does not exist, the two agree. For a volume of 0 and an empty nickname, || throws the value away and ?? keeps it.

Use ?? when 0, false or '' is a valid value, and || when any falsy value should count as missing.

Like && and ||, ?? short-circuits: if the left side is not nullish, the right side is never worked out. That makes it safe to put an expensive call on the right:

let calls = 0;
const loadDefault = () => {
calls += 1;
return 'default';
};
const saved = 'blue';
console.log(saved ?? loadDefault());
console.log(calls);

This prints:

blue
0

a ??= b assigns b to a only if a is nullish. It suits filling a cache or setting a default property once:

const cache = {};
const getPrice = (item) => {
cache[item] ??= item.length * 1.5;
return cache[item];
};
console.log(getPrice('apple'));
console.log(getPrice('fig'));
console.log(cache);

This prints:

7.5
4.5
{ apple: 7.5, fig: 4.5 }

?? cannot be combined with && or || in one expression without brackets. The language refuses to guess which should go first, so this line is a SyntaxError: Unexpected token '??':

const theme = saved || backup ?? 'light';

Brackets make the order explicit and remove the error:

const saved = null;
const backup = undefined;
const theme = (saved || backup) ?? 'light';
console.log(theme);

This prints:

light

?? pairs naturally with optional chaining, as in user.address?.city ?? 'No city given', where ?. gives undefined for a missing value and ?? replaces it.

Steve Griffith covers this topic in his video What the ?? is the nullish coalescing operator.