JavaScript · The language round
How do optional chaining and nullish coalescing work?
Short answer
Optional chaining (?.) stops and returns undefined when the left side is null or undefined. Nullish coalescing (??) returns the right side only for those two values, not for 0 or "".
Both operators reduce defensive code, but they solve different problems. Optional chaining guards a property or call. Nullish coalescing supplies a fallback without treating every falsy value as missing.
const user = { profile: null };
console.log(user.profile?.name); // undefined
console.log(user.profile.name); // TypeErrorWhat counts as nullish
const count = 0;
const name = "";
console.log(count || 10); // 10
console.log(count ?? 10); // 0
console.log(name || "guest"); // "guest"
console.log(name ?? "guest"); // ""obj?.propguards property accessobj?.[key]guards computed accessfn?.()guards a function calla ?? bfalls back only whenaisnullorundefineda?.b ?? ccombines both: guard the access, then supply a default
Optional chaining short-circuits the entire chain. Once a guard fails, the rest of the property access or call is skipped. It does not throw and it does not evaluate later parts of the expression.
?? with || or && without parentheses. The language requires explicit grouping because the precedence would be ambiguous to readers.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between `||` and `??`?
- 2When does optional chaining short-circuit?
- 3Why can't you mix `??` with `||` without parentheses?
- 4How do you call a function only if it exists?
Say it in the interview
Optional chaining lets me access a property or call a function only if the value is not null or undefined; otherwise it short-circuits and returns undefined. Nullish coalescing provides a fallback only for null and undefined, unlike logical OR, which also falls back for zero and the empty string. I use optional chaining for uncertain object shapes and nullish coalescing when zero or an empty string are valid values.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.