Optional chaining vs nullish coalescing — and why not just use ||?
Quick answer
`?.` safely reads deep paths; `??` falls back only for null/undefined, unlike `||` which also triggers on 0 and ''.
In detail
`a?.b?.c` returns undefined instead of throwing when a link is nullish. `x ?? fallback` provides a default only when x is null or undefined — crucial when 0 or '' are valid values that `||` would wrongly replace.
const qty = 0;
qty || 10; // 10 (wrong — 0 is valid)
qty ?? 10; // 0 (correct)
user?.address?.city ?? "Unknown";Why interviewers ask this: Catches the subtle || vs ?? default bug.
This is 1 of 118+ questions in the JavaScript Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the JavaScript Interview Kit → ₹299