
Member-only story
A Practical Example of Nullish Coalescing
Nullish coalescing is a brand new logical operator (??
) for the JavaScript programming language. It was released along with a whole slew of other new features on April 2nd this year as part of ECMAScript version 2020 (or ES2020).
This new operator is very similar to the logical OR (||
) operator, with the exception that it only returns the right-hand side operand when the left-hand side operand evaluates to being nullish. This means that nullish coalescing returns the right-hand side operand when the left-hand side evaluates to undefined
or null
, but not false
, 0
, or ""
as it will with the logical OR operator.
// These will return the left-hand side operand
// with nullish coalescing, but not ORfalse || true // returns true
false ?? true // returns false0 || true // returns true
0 ?? true // returns 0"" || true // returns true
"" ?? true // returns ""// These will return the right-hand side operand
// with nullish coalescing, same as ORundefined || true // returns true
undefined ?? true // returns truenull || true // returns true
null ?? true // returns true