Combining ?? with Optional Chaining
You'll learn how to safely navigate deep object structures while providing fallback values when properties are missing or nullish.
The Perfect Pairing
Optional chaining (?.) and nullish coalescing (??) are like two puzzle pieces designed to fit together. While ?. safely stops traversal when it hits null or undefined, it returns undefined in those cases. The ?? operator then lets you provide a meaningful default value instead of leaving undefined hanging around.
Think of it like exploring a building: ?. lets you safely walk through doors that might not exist (without crashing), while ?? gives you a backup plan when you hit a dead end.
How They Work Together
When you chain property access with ?., the entire expression short-circuits to undefined if any part is nullish. You can then use ?? to catch that undefined and substitute a sensible default:
const user = {
profile: {
settings: {
theme: 'dark'
}
}
};
// Safely access nested property with fallback
const theme = user?.profile?.settings?.theme ?? 'light';
// 'dark'
const fontSize = user?.profile?.settings?.fontSize ?? 16;
// 16 (property doesn't exist, so ?? provides default)
const deletedUser = null;
const name = deletedUser?.profile?.name ?? 'Guest';
// 'Guest' (short-circuits at deletedUser)
This pattern is incredibly common when working with API responses, configuration objects, or any data where structure isn't guaranteed. You get both safety (no errors) and sensible defaults (no undefined values polluting your application).
Key Takeaway: Combine ?. and ?? to create defensive code that safely navigates uncertain object structures while always providing meaningful fallback values—the best of both operators working in harmony.