JavaScript’s Optional Chaining

Darryl Mendonez
Level Up Coding
Published in
2 min readApr 23, 2021

--

Photo by Maria Lysenko 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…

Uncaught TypeError: Cannot read property '<prop>' of undefined

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.

Let's use this as our object…

const driver = {
name: 'Mary',
car: {
color: 'black',
make: 'Hyundai',
model: 'Elantra',
year: 2021
}
}

if statement conditional…

if (driver && driver.car) {
console.log(driver.car.model);
}

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.

console.log(driver && driver.car && driver.car.model);

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.

console.log(driver?.car?.model);

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 💥

--

--