What is nullish coalescing in TypeScript?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex TypeScript topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
The nullish coalescing operator (??) returns the right-hand side operand when the left-hand side is null or undefined — and only then. It is different from the logical OR (||) which also triggers for any falsy value (like 0, "", false). Example: const port = userConfig.port ?? 3000 — if port is null or undefined, use 3000; but if it is 0 (a valid port), keep 0. With ||, 0 would be treated as falsy and replaced with 3000 — a common bug. Nullish assignment (??=): user.name ??= "Anonymous" — assigns only if name is null/undefined. Combine with optional chaining: const name = user?.profile?.displayName ?? "Guest" — clean and safe default value. TypeScript infers the result type correctly, excluding null and undefined from the result when the right-hand side is a non-nullish type.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex TypeScript answers easy to follow.