Sub topic 3
Precise Defaults with ??
This chapter assumes you already know what makes a value nullish versus merely falsy, and why || replaces values like 0 and "" that you meant to keep. Both topics were covered earlier. Here we look closely at the nullish coalescing operator ??: what it does, the order it evaluates things in, how it differs from default parameters and explicit checks, and the edge cases that come up in real code.
The Rule in One Sentence
The expression a ?? b returns a unless a is null or undefined. In those two cases it returns b.
The operator never looks at whether a is truthy. It only asks one question: is the left side nullish? So 0, "", false and NaN all pass through unchanged.
const settings = { volume: 0, title: "" };
console.log(settings.volume || 50); // 50 (0 is falsy, so it is replaced)
console.log(settings.volume ?? 50); // 0 (0 is not nullish, so it is kept)
console.log(settings.title ?? "Untitled"); // ""
console.log(settings.missing ?? "fallback"); // "fallback"The last line shows the most common case. Reading a property that does not exist gives undefined, so ?? steps in with the fallback.
Side-by-Side Results
The table below shows what each operator returns for every kind of left operand, using "default" as the right operand.
| Left value `a` | `a \ | \ | "default"` | `a ?? "default"` |
|---|---|---|---|---|
| `undefined` | `"default"` | `"default"` | ||
| `null` | `"default"` | `"default"` | ||
| `0` | `"default"` | `0` | ||
| `-0` | `"default"` | `-0` | ||
| `0n` | `"default"` | `0n` | ||
| `""` | `"default"` | `""` | ||
| `false` | `"default"` | `false` | ||
| `NaN` | `"default"` | `NaN` | ||
| `"text"` | `"text"` | `"text"` | ||
| `{}` or `[]` | the object | the object |
The two operators disagree only on the middle rows, which are the falsy values that are not nullish. If a real value in your data could ever land in one of those rows, || will quietly throw it away.
How ?? Evaluates Its Operands
The operator works in a fixed order:
That order has two practical consequences.
The Right Side Is Lazy
The right operand runs only when it is needed. If computing the default is expensive or has side effects, those costs appear only when the left side is nullish.
function loadDefaultTheme() {
console.log("loading default theme...");
return "light";
}
const savedTheme = "dark";
const missingTheme = undefined;
const t1 = savedTheme ?? loadDefaultTheme(); // nothing logged
const t2 = missingTheme ?? loadDefaultTheme(); // logs "loading default theme..."
console.log(t1, t2); // dark lightThis is called short-circuit evaluation. || and && work the same way. You can safely put a function call, a new expression, or even a throw helper on the right:
function required(name) {
throw new Error(`Missing required option: ${name}`);
}
function connect(options) {
const host = options.host ?? required("host");
const port = options.port ?? 5432;
return `${host}:${port}`;
}
console.log(connect({ host: "db.local", port: 0 })); // db.local:0
try {
connect({});
} catch (err) {
console.log(err.message); // Missing required option: host
}The Left Side Is Evaluated Exactly Once
Before ?? existed, people wrote the check by hand:
const value = obj.prop !== null && obj.prop !== undefined ? obj.prop : fallback;That version reads obj.prop up to three times. If obj.prop is a getter with side effects, or if the left side is a function call, the results can differ. ?? evaluates the left side once and reuses the result.
let reads = 0;
const config = {
get port() {
reads++;
return undefined;
}
};
const manual = config.port !== null && config.port !== undefined ? config.port : 8080;
console.log(manual, reads); // 8080 2
reads = 0;
const coalesced = config.port ?? 8080;
console.log(coalesced, reads); // 8080 1The same applies to calls like getUserSetting("volume") ?? 50, where repeating the call would mean extra work or possibly a different answer.
Chaining Several Fallbacks
?? groups from left to right, so you can line up several candidates and the first non-nullish one wins.
const cliFlag = undefined;
const envVar = null;
const configFile = 0;
const builtIn = 10;
const retries = cliFlag ?? envVar ?? configFile ?? builtIn;
console.log(retries); // 0The expression a ?? b ?? c runs as (a ?? b) ?? c. Each step returns its left side if that side is present, so the chain stops at the first value that is not null or undefined. Here that value is configFile, even though it is 0. With ||, the result would have been 10, which ignores a setting the user wrote down on purpose.
This pattern fits layered configuration well, where you have command-line flags, then environment variables, then a config file, then built-in defaults.
?? Versus Default Parameters
JavaScript also has default parameters, function f(x = 5). These look like they do the same job, but they trigger on a narrower condition: only undefined, not null.
function withDefaultParam(limit = 20) {
return limit;
}
function withCoalescing(limit) {
return limit ?? 20;
}
console.log(withDefaultParam(undefined)); // 20
console.log(withDefaultParam(null)); // null
console.log(withDefaultParam(0)); // 0
console.log(withCoalescing(undefined)); // 20
console.log(withCoalescing(null)); // 20
console.log(withCoalescing(0)); // 0The null case is the one that catches people out. JSON has no undefined, so APIs and databases often send null for "no value". If that null reaches a default parameter, the default never applies.
The same rule holds for destructuring defaults:
const { pageSize = 25 } = { pageSize: null };
console.log(pageSize); // null
const payload = { pageSize: null };
const size = payload.pageSize ?? 25;
console.log(size); // 25| Mechanism | Replaces `undefined` | Replaces `null` | Replaces `0`, `""`, `false` | Column | Column |
|---|---|---|---|---|---|
| Default parameter `x = d` | Yes | No | No | ||
| Destructuring default `{ x = d }` | Yes | No | No | ||
| `x ?? d` | Yes | Yes | No | ||
| `x \ | \ | d` | Yes | Yes | Yes |
Choose based on what absence looks like in your data. If null can show up and should mean "use the default", use ??. If null is a meaningful value that the caller sent on purpose (for example, "clear this field"), a default parameter that keeps null may be exactly what you want.
Equivalent Explicit Checks
Sometimes you need to support code that cannot use ??, or you want to understand what a transpiler produces. The operator is equivalent to this:
function coalesce(a, getB) {
const left = a;
return left !== null && left !== undefined ? left : getB();
}
console.log(coalesce(0, () => 99)); // 0
console.log(coalesce(null, () => 99)); // 99You will also see the shorter loose-equality form left == null, which is true for both null and undefined and nothing else. Tools like Babel and TypeScript output something close to (_a = expr) !== null && _a !== void 0 ? _a : fallback, with a temporary variable so the left side is evaluated only once.
Choosing Between ?? and ||
Ask one question about the left operand: can a falsy value be a legitimate answer?
- Counts, prices, indexes, coordinates, volumes and timeouts can all be
0. Use??. - Boolean flags such as
enabled: falseare real choices. Use??. - Strings where an empty string is meaningful, such as a deliberately blank label, need
??. - If you truly want to treat every falsy value as missing, for example replacing an empty search box with a placeholder,
||states that intent. Writing it on purpose is fine; the bug comes from writing it by habit.
const userInput = "";
const placeholder = userInput || "Search..."; // empty input should show placeholder
const savedLabel = "";
const label = savedLabel ?? "Untitled"; // a blank label was chosen on purpose
console.log(placeholder); // Search...
console.log(JSON.stringify(label)); // ""Common Mistakes
- Expecting
??to catch empty strings or zero. It will not. If""should become a default, you need||or an explicit check. - Using
??on a value that cannot be nullish. For example,arr.length ?? 0never uses the fallback. That is harmless, but it is noise that suggests the author was unsure what the value could be. - Assuming a default parameter handles
null. As shown above, it only handlesundefined. - Putting side effects in the left operand and expecting them to run twice. The left side runs exactly once.
- Relying on the right side always running. It is lazy. If you need a side effect every time, move it out of the expression.
Exercise
What does this code log, and why? const a = null; const b = false; const c = "x"; console.log(a ?? b ?? c);
Show answer
It logs false. The chain runs as (a ?? b) ?? c. a is null, so the first step returns b, which is false. false is not nullish, so the second step returns it and c is never used.
Exercise
A function is declared as function render(width = 100) { return width; } and is called with data from a JSON API, render(response.width), where response.width is null. What is returned, and how would you change the function so that both null and undefined become 100 while 0 is still kept?
Show answer
It returns null, because default parameters only apply to undefined. Rewrite it as function render(width) { return width ?? 100; }. null and undefined then become 100, and 0 is returned unchanged.
Exercise
How many times does "computing" get logged? function d() { console.log("computing"); return 1; } const xs = [0, null, "", undefined, NaN]; xs.forEach(x => x ?? d());
Show answer
Twice. The right operand runs only for the nullish elements, null and undefined. 0, "" and NaN are falsy but not nullish, so d() is skipped for them.