Ask any question about JavaScript here... and get an instant response.
How can I safely access nested object properties using optional chaining and provide a default value with nullish coalescing?
Asked on Nov 23, 2025
Answer
Optional chaining and nullish coalescing are modern JavaScript features that allow you to safely access nested object properties and provide default values if those properties are undefined or null.
const user = {
profile: {
name: "Alice",
address: {
city: "Wonderland"
}
}
};
const city = user.profile?.address?.city ?? "Default City";
console.log(city); // Outputs: Wonderland
const country = user.profile?.address?.country ?? "Default Country";
console.log(country); // Outputs: Default CountryAdditional Comment:
✅ Answered with JavaScript best practices.- The "user.profile?.address?.city" uses optional chaining to safely access the "city" property.
- The "??" operator provides a default value if the accessed property is "undefined" or "null".
- In the example, "city" is found, so "Wonderland" is printed. "country" is not found, so "Default Country" is printed.
- This approach prevents runtime errors when accessing deep properties of an object.
Recommended Links:
