Optional Chaining and Coalescing

Introduction: The Problem of Missing Data

In our previous lessons, we learned how to structure data using objects and arrays, and how to unpack that data efficiently using destructuring. However, in real-world programming, data is rarely perfect. You will often receive information from a database or an external API where certain pieces of information are missing.

If you try to access a property on a value that is null or undefined while moving through a nested object, JavaScript will throw an error and stop your entire program from running. This is one of the most common causes of crashes in web applications.

To help us write safer code, modern JavaScript introduced two powerful tools: optional chaining (?.) and nullish coalescing (??). These operators allow us to navigate through uncertain data structures without the fear of breaking our application.

Optional Chaining Basics

The optional chaining operator, written as ?., allows you to read the value of a property located deep within a chain of connected objects without needing to check if each reference in the chain is valid. Normally, if you try to access a property on something that is null or undefined, JavaScript stops immediately with a TypeError.

When you use the ?. operator, JavaScript performs a quick check. If the value before the ?. is null or undefined, the expression "short-circuits" and returns undefined instead of crashing. This makes your code much cleaner because you no longer need to write long strings of if statements just to see if a nested object exists before you try to use it.

Chaining Through Deeply Nested Structures

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal