JavaScript’s Option Chaining Operator, Explained

Stop me if you’ve encountered this problem before:

You’re coding in JavaScript and want to access a property of a property of an object — let’s say a song object has an artist attribute, and that artist has a name. Like this:

let artist = {
name: "Elvis Presley",
albums: [
{
title: "Elvis Presley",
year: 1956,
chartPosition: 1
},
{
title: "Elvis",
year: 1956,
chartPosition: 1
},
{
title: "Elvis' Christmas Album",
year: 1957,
chartPosition: 1
}
]
}

You try to call artist.albums[0].year, and you get 1956. Great!

Now let’s say you wanted to access the year of the fourth album in the list. So you type artist.albums[3].year and you get…

Oops. I’m sure you can see the problem here — there is no fourth album in the list.

If you were just trying to access artist.albums[3], you’d just get a return value of ‘undefined’ since artist.albums[3] doesn’t exist. But because you’re now trying to access a property of that undefined value, JavaScript throws an error.

This is a trivial example, but it’s an issue that comes up all the time. For a long time, the easiest workaround was to just check if a value existed before trying to access its properties. Something like:

let importantYear = artist.albums[3] && artist.albums[3].year

This expression evaluates artist.albums[3] and checks if it’s a truthy value — in other words, if it’s anything other than undefined, null, NaN, 0, false, or an empty string. If it is a truthy value, JavaScript will assign artist.albums[3].year to the importantYear variable.

Since artist.albums[3] is not truthy — it’s undefined, a falsy value — the value of undefined gets assigned to the variable instead.

This way, you avoid that TypeError from earlier, because it only looks for the year property of artist.albums[3] if artist.albums[3] is truthy.

The relatively new option chaining operator in JavaScript avoids having to use this pattern. Instead, you just type artist.albums[3]?.year. The ?. operator tells JavaScript to check if the value before it is truthy, and only then look for the property or method after the operator.

Much simpler!

There are all kinds of uses for this, and you can check out the docs if you’re interested in learning more.

Either way, it’s a super helpful tool to have in your arsenal.

--

--

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
Alyssa Lerner First

Alyssa Lerner First

Software developer and science/tech writer. Python, Ruby on Rails, JavaScript, React/Redux, Java. Fascinated by the amazing stories behind today’s tech.