Optional chaining: ?.
When accessing nested properties, if an intermediate one is undefined or null,
JavaScript throws an error. The ?. operator avoids the problem: if something doesn't exist,
it returns undefined instead of failing.
const user = { profile: { name: "Ana" } };
console.log(user.profile?.name); // "Ana"
console.log(user.account?.email); // undefined (doesn't blow up)
Without ?., user.account.email would throw an error because account is
undefined.
Nullish coalescing: ??
The ?? operator returns the right-hand side only if the left one is null or
undefined. It's ideal for default values:
const name = user.name ?? "Anonymous";
Why not use ||?
|| treats values like 0, "" or false as "falsy", which can lead to
surprises. ?? only reacts to null/undefined:
const quantity = 0;
console.log(quantity || 10); // 10 ❌ (0 is valid but ignored)
console.log(quantity ?? 10); // 0 ✅ (respects the 0)
Combined, ?. and ?? make data access very robust:
const city = user.address?.city ?? "Unknown";
Examples
Safe access with default value
const config = { theme: { color: "blue" } };
const color = config.theme?.color ?? "black";
const font = config.typography?.font ?? "Arial";
console.log(color); // "blue"
console.log(font); // "Arial" (didn't exist)