December 24, 2019
Let’s look at a use-case that’s not too uncommon:
js1const definition = dictionary.words &&2dictionary.words.apple &&3dictionary.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.
coffeescript1solipsism = true if mind? and not world?23speed = 04speed ?= 1556footprints = yeti ? "bear"78zip = 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:
js1// solipsism = true if mind? and not world?23// speed = 04// speed ?= 1556footprints = yeti ?? "bear" // nullish coalescing78zip = lottery.drawWinner?().address?.zipcode // optional chaining910// Hence, the first example would look like:11const 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.
Built by Jayant Bhawal who is from India, trying to do funny stuff on the Web. You should follow him on Twitter