When Not to Use Optional Chaining
You'll learn: when optional chaining masks serious bugs that explicit checks would catch.
Optional chaining (?.) is powerful, but it can hide problems by silently returning undefined instead of forcing you to confront bad logic or data.
When Explicit Checks Are Better
1. Required Data That Should Always Exist
If a property should always be there, optional chaining hides the bug:
function processUser(user) {
// BAD: Silently fails if user.name is missing
console.log(user?.name?.toUpperCase());
// GOOD: Fails loudly, revealing the real problem
if (!user || !user.name) {
throw new Error('User must have a name');
}
console.log(user.name.toUpperCase());
}
2. API Contracts You Control
If you control the data structure, optional chaining suggests uncertainty where there shouldn't be any:
// BAD: Implies the structure might be incomplete
const fullName = customer?.profile?.name;
// GOOD: Trust your own API contract
const fullName = customer.profile.name;
3. Debugging and Error Discovery
Optional chaining can create "ghost errors" where everything seems fine but produces wrong results:
// Returns undefined silently—was it a typo? Missing data?
const result = data?.resutls?.items; // "resutls" typo!
// Throws immediately, revealing the typo
const result = data.results.items;
The Analogy
Think of optional chaining like a car that never makes noise when something's wrong. Sure, it keeps running smoothly, but you won't know your brakes are failing until it's too late. Sometimes you want the warning light.
Key Takeaway: Use optional chaining for genuinely optional data, but prefer explicit checks for required data or when you need errors to surface problems early.