Sub topic 2
Why || Gets Defaults Wrong
This chapter assumes you know JavaScript variables, objects and functions, and that you understand truthy and falsy values and the || and && operators. The previous chapter showed that only null and undefined count as nullish. This chapter explains why that matters: the most common way of writing default values in JavaScript, value || fallback, uses falsiness rather than nullishness, and the gap between the two causes real bugs.
How || Actually Evaluates
Many developers read a || b as "a or b, as a boolean." In JavaScript, || does not return a boolean. It returns one of its operands:
- Evaluate the left operand.
- If it is truthy, return it and never evaluate the right operand.
- Otherwise, evaluate and return the right operand, whatever it is.
Because the result is an operand, || works as a value selector:
console.log("Ada" || "Anonymous"); // "Ada"
console.log(null || "Anonymous"); // "Anonymous"
console.log(0 || ""); // "" (both falsy, so the last operand wins)
console.log(null || 0); // 0
console.log(0 || null); // nullThe last three lines show that || gives no guarantee the result is meaningful. It only returns the first truthy operand, or the final operand if none are truthy.
The Default-Value Idiom
Before ES2015 added default parameters and ES2020 added ??, || was the standard way to fill in missing values:
function connect(options) {
options = options || {};
var host = options.host || "localhost";
var port = options.port || 8080;
return host + ":" + port;
}
console.log(connect()); // "localhost:8080"
console.log(connect({ host: "example.com" })); // "example.com:8080"This works when every valid value is truthy. A non-empty hostname is always truthy, and so is any non-zero port. The idiom spread through libraries, tutorials and codebases because it is short and usually works. It fails once a falsy value is also a legitimate input.
The Falsy Values That Get Replaced
The intent behind value || fallback is almost always "use the fallback when there is no value." What the code actually says is "use the fallback when the value is falsy." The two only match when the value is null or undefined.
| Value | Falsy? | Nullish? | `value \ | \ | "default"` | Usually a valid input? |
|---|---|---|---|---|---|---|
| `undefined` | Yes | Yes | `"default"` | No, it means missing | ||
| `null` | Yes | Yes | `"default"` | No, it means deliberately empty | ||
| `false` | Yes | No | `"default"` | Yes, a boolean setting | ||
| `0` and `-0` | Yes | No | `"default"` | Yes, a count, index or amount | ||
| `0n` | Yes | No | `"default"` | Yes, a BigInt zero | ||
| `""` | Yes | No | `"default"` | Often, such as a cleared field | ||
| `NaN` | Yes | No | `"default"` | Rarely, but hiding it can mask a bug |
Six of the rows replace a value that the caller passed on purpose. Only the first two match what the developer meant.
Bugs This Causes in Practice
Numeric zero
Zero is the classic victim. Volume levels, retry counts, timeouts, prices, quantities and array indexes can all legitimately be 0.
function createPlayer(options) {
return {
volume: options.volume || 50,
retries: options.retries || 3,
startAt: options.startAt || 10,
};
}
console.log(createPlayer({ volume: 0, retries: 0, startAt: 0 }));
// { volume: 50, retries: 3, startAt: 10 }The user asked for silence, no retries and playback from the beginning. They got none of those. Nothing throws, so the bug shows up only as wrong behavior, usually reported by a confused user.
Boolean flags that default to true
|| cannot represent false for a setting whose default is true:
function setup(options) {
const autoplay = options.autoplay || true;
const showControls = options.showControls || true;
return { autoplay, showControls };
}
console.log(setup({ autoplay: false, showControls: false }));
// { autoplay: true, showControls: true }false || true is always true, so the expression ignores the input entirely. Linters often flag this pattern because it makes the setting impossible to turn off.
Empty strings
An empty string can mean "the user cleared this field on purpose":
const profile = { nickname: "", bio: "" };
const nickname = profile.nickname || "Guest";
const bio = profile.bio || "This user has not written a bio yet.";
console.log(nickname); // "Guest"
console.log(bio); // "This user has not written a bio yet."Whether this is a bug depends on your product. If clearing the nickname should show "Guest", || does what you want. If an empty value should be saved and shown as empty, as with an optional suffix or a separator character, || overwrites the user's choice.
Data from APIs and storage
The problem gets worse at system boundaries. JSON responses, query strings, form inputs and localStorage often contain 0, false or "" as real data:
const apiResponse = { unreadCount: 0, isAdmin: false, middleName: "" };
const unread = apiResponse.unreadCount || "unknown";
const admin = apiResponse.isAdmin || null;
console.log(unread); // "unknown" (the server said 0)
console.log(admin); // null (the server said false)Code further along may now treat "unknown" as an error state, or treat null as "permissions not loaded yet" and show a spinner indefinitely.
The Same Problem with && Guards
The partner idiom obj && obj.prop has the mirror-image problem. It is meant to read a property only when the object exists, but it short-circuits on any falsy left operand and returns that operand:
const cart = { count: 0 };
const message = cart.count && `${cart.count} items in cart`;
console.log(message); // 0, not undefined and not a message
const title = "";
const upper = title && title.toUpperCase();
console.log(upper); // ""In UI frameworks that render whatever value an expression produces, a stray 0 from this pattern appears on screen. The guard was meant to ask "does this exist?" but it actually asks "is this truthy?"
Pre-ES2020 Workarounds
Before ?? existed, correct code had to check for nullish values explicitly. You will still see these forms in older codebases.
function withDefault(value, fallback) {
return value === null || value === undefined ? fallback : value;
}
console.log(withDefault(0, 50)); // 0
console.log(withDefault(false, true)); // false
console.log(withDefault("", "Guest")); // ""
console.log(withDefault(undefined, 50)); // 50
console.log(withDefault(null, 50)); // 50A shorter version uses loose equality, because value == null is true only for null and undefined:
const options = { retries: 0 };
const retries = options.retries == null ? 3 : options.retries;
console.log(retries); // 0Both workarounds are correct but noisy. The variable appears twice, and the ternary hides the intent. That noise is the reason the language added a dedicated operator, which the next chapter covers.
Default Parameters Are Not a Full Fix
ES2015 default parameters look like they solve the problem, and they handle falsy values correctly. They have a different gap, though: they apply only when the argument is undefined, not when it is null.
function greet(name = "guest") {
return `Hello, ${name}`;
}
console.log(greet()); // "Hello, guest"
console.log(greet(undefined)); // "Hello, guest"
console.log(greet(0)); // "Hello, 0"
console.log(greet("")); // "Hello, "
console.log(greet(null)); // "Hello, null"Destructuring defaults follow the same rule:
const { limit = 10 } = { limit: null };
console.log(limit); // nullAPIs and databases often send null for missing fields, so destructuring defaults can let null through to code that expects a number. Default parameters also only work for parameters and destructured bindings. They don't help with an arbitrary expression in the middle of a function.
When || Is the Right Choice
|| is not wrong in itself. It answers a different question. Use it when every falsy value really should be replaced:
- Showing a display label where an empty string is as useless as a missing one:
user.displayName || user.email. - Choosing between several candidates where any falsy value means "try the next one":
envValue || configValue || "production". - Working with values that can never be validly falsy, such as DOM elements, which are either an object or
null.
The decision rule is short. Use || if 0, false and "" should be replaced. If they should be kept, you need a nullish check. Write the choice down in a comment when it isn't obvious, because a later reader cannot tell from || alone whether replacing falsy values was intended.
Exercise
What does this code print, and which lines probably do not match the developer's intent? const cfg = { delay: 0, verbose: false, prefix: "", name: null }; console.log(cfg.delay || 200); console.log(cfg.verbose || true); console.log(cfg.prefix || ">"); console.log(cfg.name || "app");
Show answer
It prints 200, true, ">" and "app". The first three lines most likely go against the intent: a delay of 0, verbose set to false and an empty prefix were all set on purpose, and || replaced them because they are falsy. Only the last line is clearly correct, because null means the name is missing. The verbose line can never produce false.
Exercise
Rewrite const pageSize = query.pageSize || 25; without ?? so that a pageSize of 0 is kept, while both null and undefined fall back to 25.
Show answer
const pageSize = query.pageSize == null ? 25 : query.pageSize; The loose check == null matches exactly null and undefined, so 0 passes through unchanged. An equivalent longer form is query.pageSize === null || query.pageSize === undefined ? 25 : query.pageSize.
Exercise
A function is declared as function load(limit = 10) { return limit; }. What do load(0), load(null) and load() return, and why might the null case cause a bug when the argument comes from a JSON API?
Show answer
load(0) returns 0, load(null) returns null, and load() returns 10. Default parameters apply only when the argument is undefined. JSON has no undefined, so APIs usually send missing fields as null. That null goes straight past the default, and code expecting a number then receives null.