Optional Chaining
Nested data can quickly become hard to work with. In production systems, you will regularly deal with objects nested 3 to 4 levels deep.
When using the normal dot (.) operator, if the object on the left side of the dot is null or undefined, JavaScript will throw a fatal TypeError at runtime, crashing that execution thread!
The Problem
const tournament = {
prize: {
units: "dollars",
value: 100,
},
};
// 'referee' does not exist on tournament
// This will throw: TypeError: Cannot read properties of undefined (reading 'height')
const h = tournament.referee.height;
The Solution: Optional Chaining
JavaScript introduced the optional chaining operator (?.) to make dealing with uncertain data safer.
If the property before the ?. does not exist, the evaluation short-circuits and simply returns undefined, completely avoiding the crash.
const tournament = {
prize: {
units: "dollars",
value: 100,
},
};
// Safe access:
const h = tournament.referee?.height;
console.log(h); // Output: undefined
Optional chaining is incredibly valuable when parsing API responses or handling network payloads where you cannot guarantee the exact shape of the data.