Sub topic 9
Nullish Coalescing with ??
This chapter assumes you already know how || returns its first truthy operand and how short-circuit evaluation skips the right-hand side. It also assumes you have seen the default-value trap from the previous chapter, where || throws away valid values such as 0 and "". The nullish coalescing operator ?? was added in ES2020 to fix that trap. It is supported in all current browsers and in Node.js 14 and later.
What "Nullish" Means
A value is nullish if it is null or undefined. No other value counts. Nullish is a much smaller group than falsy:
| Value | Falsy? | Nullish? |
|---|---|---|
| `null` | yes | yes |
| `undefined` | yes | yes |
| `false` | yes | no |
| `0`, `-0`, `0n` | yes | no |
| `""` | yes | no |
| `NaN` | yes | no |
| `"0"`, `[]`, `{}` | no | no |
The operator a ?? b evaluates a. If a is nullish, the result is b. In every other case the result is a, whatever its value.
|| Versus ?? Side by Side
The difference shows up only when the left side is falsy but not nullish. These are exactly the values that are often valid data:
const settings = { volume: 0, name: "", muted: false };
console.log(settings.volume || 50); // 50 (0 is lost)
console.log(settings.volume ?? 50); // 0 (0 is kept)
console.log(settings.name || "Anonymous"); // "Anonymous"
console.log(settings.name ?? "Anonymous"); // ""
console.log(settings.muted || true); // true (false is lost)
console.log(settings.muted ?? true); // false
console.log(settings.theme ?? "light"); // "light" (missing property is undefined)The question to ask when you choose between them is: "Which values should trigger the default?"
- If only a missing value should trigger it, use
??. - If any falsy value should trigger it, use
||.
?? is usually right for configuration, numbers, counts, booleans, and API fields where 0, false, or "" mean something. || is still reasonable when an empty string really means "nothing was given", such as a blank text input.
function greet(rawName) {
// A blank input should fall back too, so || is the right choice here.
const name = rawName.trim() || "guest";
return `Hello, ${name}`;
}
console.log(greet(" ")); // "Hello, guest"
console.log(greet("Ada")); // "Hello, Ada"?? Short-Circuits Too
Like || and &&, ?? evaluates its right operand only when it needs to. When the left side is not nullish, the right side never runs. That makes it safe to put expensive or side-effecting work on the right:
let calls = 0;
function loadDefault() {
calls += 1;
return { theme: "light" };
}
const cached = { theme: "dark" };
const missing = null;
const a = cached ?? loadDefault();
const b = missing ?? loadDefault();
console.log(a.theme, b.theme, calls); // "dark" "light" 1loadDefault() ran once, for missing. It was skipped for cached.
The left operand is evaluated exactly once. This matters when you compare ?? with the older long-hand version:
let reads = 0;
function getValue() {
reads += 1;
return 0;
}
// Long-hand: getValue() runs twice
const v1 = getValue() !== null && getValue() !== undefined ? getValue() : 10;
reads = 0;
// ?? : getValue() runs once
const v2 = getValue() ?? 10;
console.log(v1, v2, reads); // 0 0 1Chaining Several Fallbacks
?? is left-associative, so a ?? b ?? c means (a ?? b) ?? c. The result is the first operand that is not nullish. If every operand is nullish, the result is the last one.
const cliFlag = undefined;
const envValue = null;
const configValue = 0;
const port = cliFlag ?? envValue ?? configValue ?? 8080;
console.log(port); // 0
const host = undefined ?? null;
console.log(host); // null (the last operand, even though it is nullish)This pattern fits layered settings well: command-line flag, then environment, then config file, then a hard-coded default. With ||, a deliberate 0 in the config file would be skipped and you would get 8080.
How ?? Relates to Default Parameters
Function default parameters and destructuring defaults look similar, but they trigger on a narrower condition: only undefined, not null.
function connect(timeout = 1000) {
return timeout;
}
console.log(connect()); // 1000
console.log(connect(undefined)); // 1000
console.log(connect(null)); // null (default not applied)
console.log(connect(0)); // 0
function connectSafe(timeout) {
return timeout ?? 1000;
}
console.log(connectSafe(null)); // 1000The same rule applies to destructuring:
const { retries = 3 } = { retries: null };
console.log(retries); // null
const response = { retries: null };
const retries2 = response.retries ?? 3;
console.log(retries2); // 3Common Errors
Expecting ?? to catch NaN or empty strings
NaN and "" are falsy, but they are not nullish, so ?? keeps them:
const parsed = Number("abc"); // NaN
console.log(parsed ?? 0); // NaN
console.log(Number.isNaN(parsed) ? 0 : parsed); // 0If you need to reject invalid numbers, test for that directly. ?? only answers the question "is it missing?".
Replacing every || with ?? automatically
A blanket find-and-replace changes behavior wherever the code relied on falsy fallbacks. Examples are input.value || "N/A" for blank fields, and list.length || "empty". Review each case by asking which values should trigger the default.
Mixing ?? with || or && without parentheses
JavaScript rejects a || b ?? c and a ?? b && c with a SyntaxError. You must add parentheses to show which grouping you mean. The precedence chapter covers this in detail. For now, remember that the parser will stop you if you forget.
const x = (null || undefined) ?? "default";
console.log(x); // "default"Confusing ?? with a null check on the whole expression
a.b ?? "x" protects you only when a.b is nullish. If a itself is null, reading .b throws a TypeError before ?? ever runs:
const user = null;
// console.log(user.name ?? "anon"); // TypeError: Cannot read properties of nullThe fix is optional chaining, which the next chapter covers.
The Loose-Equality Shortcut
Before ES2020, a common idiom was x != null. Loose equality treats null and undefined as equal to each other and to nothing else, so this is a precise nullish check:
function orDefault(x, fallback) {
return x != null ? x : fallback;
}
console.log(orDefault(0, 5)); // 0
console.log(orDefault(undefined, 5)); // 5
console.log(orDefault(null, 5)); // 5x ?? fallback behaves the same way, evaluates x once, and is easier to read. You will still see != null in older code and in strict-equality lint configs that allow it as an exception (ESLint's eqeqeq rule with the "smart" option, for example).
Choosing the Right Tool
| Goal | Use |
|---|---|
| Default only when a value is `null` or `undefined` | `a ?? b` |
| Default when a value is any falsy value | <code>a || b</code> |
| Default a function argument that is omitted | `function f(a = b)` |
| Default a function argument that may be `null` | `a ?? b` inside the body |
| Reject `NaN` or invalid input | An explicit test such as `Number.isNaN` |
Exercise
Predict the output of each line: console.log(0 ?? 1);, console.log(null ?? undefined);, console.log(false || null ?? "x");, console.log("" ?? "empty");
Show answer
0 prints 0, because 0 is not nullish. null ?? undefined prints undefined, because the left side is nullish so the result is the right operand, even though it is also nullish. The third line is a SyntaxError, because ?? cannot be mixed with || without parentheses, and since the error stops the whole script from parsing, no line runs at all. With that line removed, the last line prints an empty string, because "" is not nullish.
Exercise
A settings object comes from JSON: const s = JSON.parse('{"pageSize":0,"theme":null}');. Write expressions that give pageSize a default of 20 and theme a default of "light", keeping any value the user set on purpose. Explain why const { pageSize = 20, theme = "light" } = s; is wrong here.
Show answer
Use const pageSize = s.pageSize ?? 20; (gives 0) and const theme = s.theme ?? "light"; (gives "light"). The destructuring version correctly keeps pageSize as 0, but it leaves theme as null, because destructuring defaults apply only to undefined, and JSON represents missing values as null.
Exercise
The function function label(count) { return count || "none"; } returns "none" for 0. Rewrite it so that 0 is shown as 0, while null and undefined still produce "none". Then explain whether the expensive call in cache.get(key) ?? compute(key) runs when the cache holds the value false.
Show answer
function label(count) { return count ?? "none"; }. compute(key) does not run, because false is not nullish. ?? short-circuits and returns false without evaluating its right operand.