Jayant's Clipboard

Optional Chaining is ❤

December 24, 2019

Let’s look at a use-case that’s not too uncommon:

js
1
const definition = dictionary.words &&
2
dictionary.words.apple &&
3
dictionary.words.apple.definition;

Oh my, that’s an eyeful. All I wanted to get was the definition of apple, if present, in a user-created dictionary, meaning that the initial state of this dictionary could possibly be completely empty.

This has been a little painful, and has been a thing since years.

We’ve had “solutions” since long too

The fine creators of coffeescript did indeed solve this issue in a way. They introduced the Existential Operator, and this is how that looked like:

coffeescript
1
solipsism = true if mind? and not world?
2
3
speed = 0
4
speed ?= 15
5
6
footprints = yeti ? "bear"
7
8
zip = lottery.drawWinner?().address?.zipcode

Amazing right? Though a lot of this stuff has come into JS, it didn’t make an as-is introduction. In fact, many other languages too had the optional chaining operator with them, and a lot of discussion was had before they arrived on the best solution that would play nice in JS. A lot of the stuff from the coffeescript example doesn’t exist nicely in JS.

That exact example would look like this in JS:

js
1
// solipsism = true if mind? and not world?
2
3
// speed = 0
4
// speed ?= 15
5
6
footprints = yeti ?? "bear" // nullish coalescing
7
8
zip = lottery.drawWinner?().address?.zipcode // optional chaining
9
10
// Hence, the first example would look like:
11
const definition = dictionary.words?.apple?.definition;

I am a straight up fan of this thing, and I’ve been tracking progress of this since a year before it released!

Optional Chaining and Nullish Coalescing are now in Stage 4, and released into some major browsers. It was added to TypeScript 3.7 a week after it was moved to Stage 3. Soon afterwards, it was added to react-scripts 3.3.0-next.62 (with TS), and was released in the stable 3.3 build of react-scripts.


Jayant Bhawal

Built by Jayant Bhawal who is from India, trying to do funny stuff on the Web. You should follow him on Twitter