Optional Chaining with Nullish Coalescing
Published on
javascripttil
Optional Chaining with Nullish Coalescing
Today I learned how powerful the combination of optional chaining (?.) and nullish coalescing (??) can be.
The Pattern
const value = obj?.property?.nested ?? 'default';This safely accesses nested properties and provides a default value if the result is null or undefined.
Example
const user = {
profile: {
name: 'John'
}
};
// Old way
const email = user && user.profile && user.profile.email
? user.profile.email
: 'no-email@example.com';
// New way
const email = user?.profile?.email ?? 'no-email@example.com';Much cleaner!