Sub topic 3
Precise Defaults with ??
This chapter assumes you know truthy and falsy values and how || picks its result. Earlier chapters showed that null and undefined are the only nullish values, and that || replaces every falsy value, including 0 and "". Here you will learn how the nullish coalescing operator ?? fixes that.
The Rule
The expression left ?? right works like this:
- JavaScript evaluates
leftonce. - If
leftisnullorundefined, the result isright. - Otherwise, the result is
left, unchanged.
The operator only checks whether the left value is nullish. It does not convert that value to a boolean. That is why 0, "", false and NaN all pass through untouched.
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"Side by Side with ||
| Left value | `left \ | \ | "d"` | `left ?? "d"` |
|---|---|---|---|---|
| `undefined` | `"d"` | `"d"` | ||
| `null` | `"d"` | `"d"` | ||
| `0` | `"d"` | `0` | ||
| `""` | `"d"` | `""` | ||
| `false` | `"d"` | `false` | ||
| `NaN` | `"d"` | `NaN` | ||
| `"hi"` | `"hi"` | `"hi"` |
Use ?? when 0, "" or false are real answers that the user or the data chose on purpose. Use || only when you want every empty-looking value replaced, such as treating a blank search box as "no query".
The Right Side Is Lazy
?? short-circuits. If the left side is not nullish, the right side never runs. This matters when the default is expensive or has side effects.
let calls = 0;
function loadDefaultTheme() {
calls++;
return "light";
}
const saved = "dark";
const theme = saved ?? loadDefaultTheme();
console.log(theme); // "dark"
console.log(calls); // 0 (loadDefaultTheme was never called)A Worked Example: Config Merging
A common job is to merge user options with defaults, where 0 and false are valid choices.
function createServer(options = {}) {
const port = options.port ?? 8080;
const verbose = options.verbose ?? true;
const maxConnections = options.maxConnections ?? 100;
return { port, verbose, maxConnections };
}
console.log(createServer({ port: 0, verbose: false, maxConnections: null }));
// { port: 0, verbose: false, maxConnections: 100 }If you had used ||, port: 0 (often "pick any free port") would turn into 8080. verbose: false would also turn into true, so the user could never switch logging off.
?? Versus Default Parameters
Default parameters and destructuring defaults look similar, but they only trigger on undefined. ?? triggers on null as well.
function greet(name = "guest") {
return "Hello, " + name;
}
function greetNullish(name) {
return "Hello, " + (name ?? "guest");
}
console.log(greet(null)); // "Hello, null"
console.log(greetNullish(null)); // "Hello, guest"APIs and databases often send null to mean "no value". When that can happen, ?? is the safer choice.
Common Errors
- Expecting
??to catch empty strings."" ?? "x"returns"". If blank input should fall back to a default, use||, or trim the input and test it yourself. - Expecting
??to catchNaN.Number("abc") ?? 0isNaN. Check for it withNumber.isNaN. - Assuming it guards property access.
obj.a ?? 1still throws ifobjisnull. You need optional chaining for that, which comes in the next chapters.
Exercise
What does this log, and why? const qty = 0; const label = ""; console.log(qty ?? 1, label || "none", null ?? undefined ?? "end");
Show answer
It logs 0 "none" "end". 0 is not nullish, so ?? keeps it. "" is falsy, so || replaces it with "none". In the chain, null and undefined are both nullish, so the first value that is not nullish is "end".
Exercise
A function receives limit from a JSON body, where the value can be missing, null, or 0 (meaning "no results"). Write one expression that defaults to 20 only when the value is missing or null.
Show answer
const limit = body.limit ?? 20;. This keeps 0 and replaces undefined and null. A default parameter would not catch null, and || would wrongly replace 0.