Glossary / Nullish coalescing

Nullish coalescing

Nullish coalescing (??) returns its left operand unless that value is null or undefined; only then does it evaluate and return the right operand. It provides a fallback for absence while preserving valid falsy values such as zero, false, and the empty string.

Comparison with logical OR

const configuredLimit = 0;
configuredLimit || 20; // 20: zero is falsy
configuredLimit ?? 20; // 0: zero is not nullish

Use ?? when null/undefined mean “not supplied.” Use || when every falsy value should select the fallback—which is less common for numeric and form data. Neither operator validates its input. For example, NaN is falsy under ||, so a fallback may hide invalid arithmetic.

The operator short-circuits, so the right side is not evaluated for a non-nullish left side. Nullish coalescing assignment (??=) applies the same rule when assigning a fallback. The grammar requires parentheses if ?? is combined directly with && or ||, making the grouping explicit:

const result = (primary ?? secondary) || finalFallback;

Before using a fallback, decide whether explicit null means absent, invalid, or intentionally empty. API contracts should define that meaning rather than letting the operator choose accidentally.

Interview questions

  1. What does 0 ?? 5 return? Zero.
  2. What differs from ||? || uses truthiness and replaces all falsy values; ?? replaces only null and undefined.
  3. Is NaN nullish? No, although NaN || fallback uses the fallback because NaN is falsy.
  4. Why parenthesize mixtures with &&/||? JavaScript grammar prohibits unparenthesized direct mixtures to avoid ambiguous intent.

References