A Gentle Introduction to Nullish Coalescing Operator

October 11, 2021

A nullish coalescing operator is a logical operator that returns a right-side operand when the left-side operand is null or undefined. Otherwise left side operand is returned.

index.js
1console.log(false ?? 'A') // false
2console.log(0 ?? 'B') // 0
3console.log(-0 ?? 'C') // -0
4console.log(0n ?? 'D') // 0n
5console.log(null ?? 'E') // E
6console.log(undefined ?? 'F') // F
7console.log(NaN ?? 'G') // NaN
8console.log('' ?? 'H') // ''

This varies from the logical OR || operator, which returns right-side operand when the left operand is any falsy value; not only null or undefined.

index.js
1console.log(false || 'A') // A
2console.log(0 || 'B') // B
3console.log(-0 || 'C') // C
4console.log(0n || 'D') // D
5console.log(null || 'E') // E
6console.log(undefined || 'F') // F
7console.log(NaN || 'G') // G
8console.log('' || 'H') // H

The logical OR operator is better suited to provide some default value rather than passing falsy value. On the other hand, if you care only about null and undefined (ignoring other falsy values), nullish coalescing operator is the way to go!

The right-side operand is NOT evaluated if the left-side is other than null or undefined.

index.js
1const foo = () => {
2 console.log('foo was called')
3
4 return undefined
5}
6
7const bar = () => {
8 console.log('bar was called')
9
10 return null
11}
12
13const baz = () => {
14 console.log('baz was called')
15
16 return false
17}
18
19console.log(foo() ?? baz())
20// LOGS:
21// foo was called (evaluated foo function)
22// baz was called (evaluated baz function)
23// false (returned baz function)
24
25console.log(bar() ?? baz())
26// LOGS:
27// bar was called
28// baz was called (evaluated baz function)
29// false (returned baz function)
30
31console.log(baz() ?? bar())
32// LOGS:
33// baz was called (evaluated baz function)
34// false (returned baz function)

Share this post on Twitter