How do you combine optional chaining with the nullish coalescing operator to safely access a value with a fallback default?
Short answer
Chain ?. through the potentially-missing path, then use ?? immediately after to provide a fallback specifically for the case where the whole chain resolved to undefined (either because it stopped early or the final value itself was null/undefined).
Advertisement
AModel answer
Chain ?. through the potentially-missing path, then use ?? immediately after to provide a fallback specifically for the case where the whole chain resolved to undefined (either because it stopped early or the final value itself was null/undefined).
const theme = user?.settings?.theme ?? 'light';
// Falls back to 'light' if user, settings, or theme itself is null/undefinedReal-world example
Providing a sensible default UI theme or configuration value when a user's saved preferences might not exist yet.
Likely follow-ups
- What's the difference in behavior if you used || instead of ?? at the end of this chain?
Related topics