Sub topic 14
Safer Defaults with ??
This chapter assumes you know how || and && pick one of their operands and short-circuit, which the previous chapter covered. It also assumes you know which values are falsy and how null and undefined behave in comparisons. The topic here is the nullish coalescing operator, ??. It supplies a default only when a value is actually missing.
The Problem with || for Defaults
For years, JavaScript code used || to supply defaults:
function configure(options) {
const retries = options.retries || 3;
const label = options.label || 'untitled';
return { retries, label };
}
console.log(configure({})); // { retries: 3, label: 'untitled' }
console.log(configure({ retries: 0, label: '' })); // { retries: 3, label: 'untitled' }The second call is a bug. The caller asked for zero retries and an empty label, and both choices were overwritten. || falls back on every falsy value, so 0, '', false, and NaN all count as missing. In configuration objects, form inputs, and API responses, those values are often valid data.
What ?? Does
a ?? b evaluates a. If a is null or undefined, the expression evaluates b and returns it. Otherwise it returns a and never evaluates b. Together, null and undefined are called the nullish values.
function configure(options) {
const retries = options.retries ?? 3;
const label = options.label ?? 'untitled';
return { retries, label };
}
console.log(configure({})); // { retries: 3, label: 'untitled' }
console.log(configure({ retries: 0, label: '' })); // { retries: 0, label: '' }
console.log(configure({ retries: null })); // { retries: 3, label: 'untitled' }Like ||, the operator returns an operand and does not convert it to a boolean. It never coerces anything, either. The check is just "is this null or undefined?"
Side by side with ||
| Left operand | `left \ | \ | 'fb'` | `left ?? 'fb'` |
|---|---|---|---|---|
| `undefined` | `'fb'` | `'fb'` | ||
| `null` | `'fb'` | `'fb'` | ||
| `0` | `'fb'` | `0` | ||
| `''` | `'fb'` | `''` | ||
| `false` | `'fb'` | `false` | ||
| `NaN` | `'fb'` | `NaN` | ||
| `'hello'` | `'hello'` | `'hello'` |
Use || when every falsy value should mean "use the default", for example when an empty display name should show a placeholder. Use ?? when only an absent value should.
Short-Circuit Evaluation
The right operand runs only when it is needed, which matters when computing the default costs something or has side effects:
let calls = 0;
function expensiveDefault() {
calls++;
return 'computed';
}
const a = 'set' ?? expensiveDefault();
const b = null ?? expensiveDefault();
const c = 0 ?? expensiveDefault();
console.log(a, b, c, calls); // set computed 0 1expensiveDefault ran once, for b only.
Chaining and Grouping
?? groups left to right, so a chain returns the first operand that is not nullish:
const fromArgs = undefined;
const fromEnv = null;
const fromFile = 0;
console.log(fromArgs ?? fromEnv ?? fromFile ?? 8080); // 0
console.log(null ?? undefined ?? 'last'); // lastfromFile is 0, which is not nullish, so the chain stops there. With || the same chain would skip past 0 and return 8080.
Mixing with || and && is a SyntaxError
You cannot combine ?? directly with || or && unless you add parentheses. The language designers added this rule on purpose, because readers disagree about how such expressions should group.
const count = 0;
const fallback = 5;
// const bad = count ?? null || fallback; // SyntaxError
const groupedLeft = (count ?? null) || fallback; // (0) || 5 -> 5
const groupedRight = count ?? (null || fallback); // 0 is not nullish -> 0
console.log(groupedLeft, groupedRight); // 5 0The two groupings give different answers, so the parentheses carry real meaning. Mixing ?? with other operators needs no parentheses. ?? binds tighter than the conditional operator and assignment, so x ?? y ? 'a' : 'b' parses as (x ?? y) ? 'a' : 'b'. Arithmetic and comparison operators bind tighter than ??, so a ?? b + 1 means a ?? (b + 1).
Edge Cases and Gotchas
?? does not catch NaN or empty strings
?? checks only for null and undefined. Conversion results such as NaN slip through:
const raw = 'abc';
const parsed = Number(raw) ?? 0;
console.log(parsed); // NaN: NaN is not nullish
const safe = Number.isNaN(Number(raw)) ? 0 : Number(raw);
console.log(safe); // 0Put the ?? before the conversion when the input itself might be missing, for example Number(input ?? '0'). Validate the converted value separately.
Default parameters and destructuring handle only undefined
Default parameter values and destructuring defaults kick in only for undefined. They do not kick in for null. That makes them stricter than ??:
function greet(name = 'guest') {
return `hi ${name}`;
}
console.log(greet(undefined)); // hi guest
console.log(greet(null)); // hi null
function greetSafe(name) {
const who = name ?? 'guest';
return `hi ${who}`;
}
console.log(greetSafe(null)); // hi guest
const { port = 8080 } = { port: null };
console.log(port); // nullJSON has no undefined, so APIs often send null for missing fields. Destructuring defaults will not replace those nulls. Use ?? instead.
| Mechanism | Falls back on `undefined` | Falls back on `null` | Falls back on other falsy values | Column | Column |
|---|---|---|---|---|---|
| `a \ | \ | b` | yes | yes | yes |
| `a ?? b` | yes | yes | no | ||
| Default parameter / destructuring default | yes | no | no |
Pairing with optional chaining
?? is often written at the end of an optional chain, as in user.profile?.city ?? 'Unknown'. The chain produces undefined when a link is missing, and ?? replaces it. The next chapter covers ?. in detail.
Common Errors
- Replacing every
||with??without checking intent. If an empty string should fall back to a placeholder,||was correct. - Expecting
??to replaceNaN,'', orfalse. - Writing
a ?? b || cwithout parentheses, which is a SyntaxError. - Assuming a parameter default handles
nullfrom a JSON payload. - Forgetting that the right operand is skipped, so side effects placed there do not always run.
Exercise
What does each line log? (1) console.log(false ?? true); (2) console.log(undefined ?? null ?? ''); (3) const { size = 10 } = { size: null }; console.log(size ?? 20);
Show answer
(1) false, because false is not nullish. (2) '': undefined and null are both skipped, and the empty string is returned because it is not nullish. (3) 20: the destructuring default ignores null, so size is null, and then ?? replaces it with 20.
Exercise
A function reads settings.volume, which may be missing, null, or a number from 0 to 100. It currently uses const volume = settings.volume || 50;. Explain the bug and rewrite the line. Then explain why const level = settings.volume ?? 50 || 0; will not run.
Show answer
With ||, a volume of 0 (muted) is falsy and turns into 50. Write const volume = settings.volume ?? 50; so that only null or undefined fall back. The second line mixes ?? and || without parentheses, which is a SyntaxError. It needs explicit grouping, such as (settings.volume ?? 50) || 0.
Exercise
Given let n = 0; const r = 'x' ?? (n = 1); const s = undefined ?? (n += 5);, what are r, s, and n afterward?
Show answer
r is 'x', and the assignment n = 1 never runs because 'x' is not nullish. s is 5, because the left side is undefined, so n += 5 runs and takes n from 0 to 5. n is 5.