JavaScript’s Option Chaining Operator, Explained

Simplify Your Code with One of JavaScript’s Newest Features

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:

You try to call , 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 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 , you’d just get a return value of ‘undefined’ since 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:

This expression evaluates and checks if it’s a truthy value — in other words, if it’s anything other than , , , , , or an empty string. If it is a truthy value, JavaScript will assign to the variable.

Since is not truthy — it’s , 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 if is truthy.

The relatively new option chaining operator in JavaScript avoids having to use this pattern. Instead, you just type . 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.

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

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