A Gentle Introduction to Nullish Coalescing Operator
October 11, 2021A 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
console.log(false ?? 'A') // falseconsole.log(0 ?? 'B') // 0console.log(-0 ?? 'C') // -0console.log(0n ?? 'D') // 0nconsole.log(null ?? 'E') // Econsole.log(undefined ?? 'F') // Fconsole.log(NaN ?? 'G') // NaNconsole.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
console.log(false || 'A') // Aconsole.log(0 || 'B') // Bconsole.log(-0 || 'C') // Cconsole.log(0n || 'D') // Dconsole.log(null || 'E') // Econsole.log(undefined || 'F') // Fconsole.log(NaN || 'G') // Gconsole.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
const foo = () => {console.log('foo was called')return undefined}const bar = () => {console.log('bar was called')return null}const baz = () => {console.log('baz was called')return false}console.log(foo() ?? baz())// LOGS:// foo was called (evaluated foo function)// baz was called (evaluated baz function)// false (returned baz function)console.log(bar() ?? baz())// LOGS:// bar was called// baz was called (evaluated baz function)// false (returned baz function)console.log(baz() ?? bar())// LOGS:// baz was called (evaluated baz function)// false (returned baz function)