JavaScript’s Optional Chaining

Photo by Alexander Krivitskiy on Unsplash

If you’ve programmed in JavaScript then you know the benefits of using objects. They organize our data structures in a way that allows us to access values directly by looking up their keys.

And working with objects, you are certainly familiar with this appearing in your console…

This often occurs because you’re making an api call and the response has not yet completed which is very normal. To combat this, I’ve seen and handled it myself a few different ways. Using short-circuit evaluation in anif statement works.

Lets use this as our object…

if statement conditional…

Nothing wrong with this but JavaScript does have to look up driver three different times. Is driver truthy? Okay, is driver.car truthy? Cool, log driver.car.model.

This will certainly avoid the log error from appearing in your console but can we do better? Sure, we can also do short-circuit evaluation directly in the console.log.

This will also avoid the error log and save us from having to write an if statement. If any of these evaluations short-circuit the console will log undefined as opposed to looking up the next evaluation leading to the Uncaught TypeError.

Sweet! But, can we do even better? Enter optional chaining. At first glance it may seem a bit jarring because of how the question marks are placed but it cleans up our code and JavaScript only needs to access our object once.

Simple and to the point. That’s what I like.

It will check to see if driver is truthy, and then if car is, and then finally model. If any of these are falsy, it will log undefined not the Uncaught TypeError. And, of course, if they’re all truthy then it will log the value of model. Bingo, bango, bongo 💥

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store