Short-Circuiting Behavior
You'll learn how optional chaining stops evaluating the moment it hits null or undefined, preventing errors and skipping the rest of the chain.
The Safety Brake
When you use optional chaining (?.), JavaScript doesn't blindly plow forward through your entire chain of property accesses. Instead, it acts like a safety brake: the moment it encounters null or undefined, it immediately stops evaluating and returns undefined for the entire expression. The rest of the chain is never touched.
How Short-Circuiting Works
const user = null;
// Without optional chaining: CRASH
// const name = user.profile.name; // TypeError!
// With optional chaining: short-circuits at user
const name = user?.profile.name;
console.log(name); // undefined (never tried to access .profile or .name)
The moment JavaScript sees user is null, it stops. It doesn't attempt .profile, doesn't attempt .name. The entire expression immediately resolves to undefined.
Why This Matters
This behavior extends to the entire statement:
const data = { api: null };
// Short-circuits at api, never calls .getUsers() or accesses .length
const count = data.api?.getUsers()?.length;
console.log(count); // undefined
Since data.api is null, JavaScript stops there. It never attempts to call getUsers(), and never tries to access length. This is not the same as evaluating everything and replacing errors with undefined—it truly skips the remaining operations.
Key Takeaway: Optional chaining short-circuits the entire expression at the first null or undefined, immediately returning undefined and skipping all subsequent property accesses, method calls, or operations in the chain. This makes it both safe and efficient.