
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

This is pretty cool, but how can it improve the way we write code? Today I came across the perfect use of nullish coalescing. Of course there are plenty more great uses for this new operator, but I thought I’d share how it worked for me.
I was working on a modal component with the typical functionality you might find in any modal. What I was tasked with changing on this particular modal was to create a beforeClose()
hook that would be provided by the application and executed by the modal prior to closing. Additionally, I needed to make it so that if the beforeClose()
hook returned false
, closing the modal should be prevented, that way the application can control whether the modal can close when a close event is initiated, such as by clicking the “close” button.
The modal logic therefore resembles the following:
class Modal {
constructor(options =…