Nullish Coalescing ??
The fallback operator that respects 0, empty string and false as real values.
value ?? fallback?? returns the right side only when the left is null or undefined. Unlike ||, it does not fire for 0, '', or false. This is exactly what you want for defaults, config, and user input.
const volume = settings.volume ?? 100; // 0 stays 0
const label = input.value ?? 'n/a'; // '' stays ''Why it exists
Before ??, everyone wrote x || default and quietly shipped bugs whenever 0 or '' were valid. ?? narrows the fallback trigger to genuine absence.
Mixing with && / ||
JavaScript forbids combining ?? with && or || without parentheses, precisely to stop ambiguous precedence bugs. Wrap them explicitly: (a || b) ?? c.
Example
When to use it
- Supply a default page size of 20 only when the config value is null or undefined, not when it is 0.
- Use ??= to lazily initialise a cache entry the first time a key is accessed.
- Fall back to a placeholder string with ?? when an API response field is explicitly null.
More examples
Nullish coalescing vs OR
Contrasts || which treats 0 as falsy with ?? which only falls back for null or undefined.
const count = 0;
console.log(count || 10); // 10 β 0 is falsy, falls back
console.log(count ?? 10); // 0 β ?? only triggers for null/undefinedNullish assignment ??=
??= assigns a value only when the current value is null or undefined, ideal for lazy initialisation.
const cache = {};
cache.ttl ??= 3600; // set only if null or undefined
cache.ttl ??= 9999; // ignored β ttl is already 3600
console.log(cache.ttl); // 3600Chaining ?? with objects
Combines optional chaining with ?? to provide a default avatar when the profile is null.
const user = { profile: null };
const avatar = user.profile?.avatar ?? "/default.png";
console.log(avatar); // "/default.png"
Discussion