Sub topic 2
Why || Gets Defaults Wrong
This chapter assumes you know JavaScript objects and the logical operators || and &&, and that you have read the previous chapter on nullish values. It explains why the long-standing value || fallback idiom replaces values you meant to keep. The next chapter introduces the operator that fixes this.
How || actually works
The || operator does not return true or false. It returns one of its operands:
- It evaluates the left operand.
- If the left operand is truthy, it returns that operand and never evaluates the right one.
- Otherwise, it returns the right operand, whatever it is.
That behavior made || the usual way to write defaults for years:
function greet(name) {
const who = name || "guest";
return `Hello, ${who}!`;
}
console.log(greet("Ada")); // "Hello, Ada!"
console.log(greet()); // "Hello, guest!"
console.log(greet(undefined)); // "Hello, guest!"The idiom works here because no valid name is falsy, except the empty string, which you probably want to replace anyway.
The problem: falsy is broader than missing
|| checks for falsy, not for missing. Falsy covers eight values: false, 0, -0, 0n, "", NaN, null and undefined. Only the last two mean "no value was given". The others are often valid data.
const settings = { volume: 0, title: "", showHints: false };
const volume = settings.volume || 50;
const title = settings.title || "Untitled";
const showHints = settings.showHints || true;
console.log(volume); // 50 (the user muted the sound, and we undid it)
console.log(title); // "Untitled" (an intentionally blank title is lost)
console.log(showHints); // true (the user turned hints off, and we turned them back on)None of these lines throws an error. The program runs and quietly does the wrong thing. That is why this bug usually turns up in production, when a real user saves a setting of 0 or false.
Where the bug shows up
| Value kind | Valid falsy value | What ` | Column | default` does |
|---|---|---|---|---|
| Numbers | `0` (volume, count, price, index) | Replaces it with the default | ||
| Strings | `""` (blank label, empty search) | Replaces it with the default | ||
| Booleans | `false` (feature turned off) | Replaces it, often with `true` | ||
| Big integers | `0n` | Replaces it with the default |
Boolean flags are the worst case. With flag || true, the result is always true, so the user can never turn the setting off.
The old workaround
Before ES2020, the correct fix was an explicit check for null and undefined:
function withDefault(value, fallback) {
return value !== null && value !== undefined ? value : fallback;
}
const settings = { volume: 0, title: "" };
console.log(withDefault(settings.volume, 50)); // 0
console.log(withDefault(settings.title, "Untitled")); // ""
console.log(withDefault(settings.missing, "n/a")); // "n/a"Some codebases shorten the check to value == null, because loose equality treats null and undefined as equal to each other and to nothing else. Both versions are correct, but they are longer than ||, so people kept reaching for || and kept shipping the bug.
When || is still the right choice
|| is fine when every falsy value really should fall back to the default:
- Replacing an empty string as well as a missing one, as in
input.trim() || "Anonymous". - Combining real booleans, as in
isAdmin || isOwner. - Values where
0or""are not meaningful, such as a required, non-empty ID.
Ask one question before using ||: can a falsy value here be valid data? If it can, you need a nullish check instead.
Exercise
A function receives options.retries, where 0 means "do not retry". It uses const retries = options.retries || 3;. What is retries when a caller passes { retries: 0 }, and how would you fix it without using ?? ?
Show answer
retries becomes 3, because 0 is falsy and || falls through to the right operand. One fix is const retries = options.retries !== null && options.retries !== undefined ? options.retries : 3; (or options.retries == null ? 3 : options.retries), which replaces only null and undefined and keeps 0.
Exercise
Which of these values does x || "default" keep as x: "0", 0, [], NaN, " "?
Show answer
It keeps "0", [] and " ", because non-empty strings and all objects, including empty arrays, are truthy. It replaces 0 and NaN, which are falsy.