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
We often work with arrays of objects where some objects are more complete than others. Consider a list of users where some have a full profile, some have a null profile, and others are missing the profile property entirely. Without optional chaining, reaching for an email address inside these objects would be very risky.
Output:
In this example, we use u?.profile?.contact?.email to safely dig into the data. For Ada, the code finds the email successfully. For Grace, the process stops at profile because it is null. For Linus, the process stops because profile is missing.
In both cases where data was missing, the code simply returned undefined for the email variable and continued to the next user. This is much better than the program stopping with an error.
