Sub topic 8
Default Values with || and the 0 and Empty-String Trap
This chapter assumes you already know which values are falsy, that || returns one of its operands, and that || short-circuits. It also assumes you can read function parameters and object properties. Here we put those rules to work on one everyday task: supplying a fallback when a value is missing. You will see why || handles that job well in some cases and fails quietly in others.
The Classic Fallback Idiom
For most of JavaScript's history, || was the standard way to provide a default:
function greet(name) {
const who = name || "stranger";
return `Hello, ${who}!`;
}
console.log(greet("Ada")); // "Hello, Ada!"
console.log(greet()); // "Hello, stranger!"
console.log(greet(undefined)); // "Hello, stranger!"The idiom works because name || "stranger" returns name when it is truthy. When name is falsy, it returns "stranger". A missing argument is undefined, undefined is falsy, and so the fallback wins.
Problems start when "missing" and "falsy" are treated as the same thing. They are not the same. || reacts to every falsy value, so it reacts to all of these:
undefinedandnull, which usually do mean "no value"0and-0, which are often real measurements"", which can be a deliberate empty inputfalse, which is often an explicit choiceNaNand0n, which are less common but still falsy
The Trap in Action
Here is a realistic options handler. Each line looks reasonable on its own:
function createPlayer(options) {
const volume = options.volume || 50;
const name = options.name || "Guest";
const autoplay = options.autoplay || true;
return { volume, name, autoplay };
}
console.log(createPlayer({ volume: 0, name: "", autoplay: false }));
// { volume: 50, name: 'Guest', autoplay: true }The caller asked for silence, an empty name, and no autoplay. Every one of those requests was overridden:
| Property | Caller passed | Meaning | Result with `\ | \ | ` | Correct? |
|---|---|---|---|---|---|---|
| `volume` | `0` | Muted | `50` | No | ||
| `name` | `""` | Intentionally blank | `"Guest"` | Depends on intent | ||
| `autoplay` | `false` | Turn it off | `true` | No | ||
| `volume` | `undefined` | Not specified | `50` | Yes |
The autoplay line is the worst of the three. options.autoplay || true can never evaluate to false. If autoplay is truthy, you get that value. If it is falsy, you get true. The caller has no way to turn the feature off. Any x || true expression has this flaw.
None of these bugs throw an error. The code runs, the output looks plausible, and the bug shows up later as a user report like "I set the volume to zero and it plays at half volume."
Numbers from Parsing
Parsing input is another common source of the trap:
function readPageSize(input) {
return Number.parseInt(input, 10) || 20;
}
console.log(readPageSize("50")); // 50
console.log(readPageSize("abc")); // 20 (NaN replaced, as intended)
console.log(readPageSize("0")); // 20 (0 replaced, maybe not intended)The author wanted to catch NaN from bad input, and || does that. It also catches a parsed 0. Whether that matters depends on the domain. A page size of 0 is probably nonsense, so the fallback is fine there. A temperature, a discount, or an array index of 0 is perfectly valid. If 0 is legal, test for the case you actually mean:
function readOffset(input) {
const n = Number.parseInt(input, 10);
return Number.isNaN(n) ? 0 : n;
}
console.log(readOffset("0")); // 0
console.log(readOffset("15")); // 15
console.log(readOffset("abc")); // 0Writing Checks That Mean "Missing"
The fix is to stop asking "is this falsy?" and ask "is this absent?" instead. Before the nullish coalescing operator ?? existed (it gets its own chapter next), developers wrote that check by hand:
function withDefault(value, fallback) {
return value === undefined || value === null ? fallback : value;
}
console.log(withDefault(0, 50)); // 0
console.log(withDefault("", "Guest")); // ""
console.log(withDefault(false, true)); // false
console.log(withDefault(undefined, 50)); // 50
console.log(withDefault(null, 50)); // 50A shorter form you will see in older code is value == null. Loose equality treats null and undefined as equal to each other and to nothing else, so value == null is true for exactly those two values. Many style guides ban == but make an exception for this one pattern.
const volume = 0;
const result = volume == null ? 50 : volume;
console.log(result); // 0Default Parameters Are Narrower Still
Function default parameters are a related tool with a different rule. They apply only when the argument is undefined, and null does not trigger them:
function setVolume(level = 50) {
return level;
}
console.log(setVolume()); // 50
console.log(setVolume(undefined)); // 50
console.log(setVolume(0)); // 0
console.log(setVolume(null)); // nullThis means default parameters never fall into the 0 or empty-string trap. They also will not protect you from a caller, or a JSON payload, that passes null. Destructuring defaults such as const { volume = 50 } = options follow the same undefined-only rule.
| Technique | Falls back on `undefined` | on `null` | on `0`, `""`, `false`, `NaN` | Column | Column |
|---|---|---|---|---|---|
| `value \ | \ | d` | Yes | Yes | Yes |
| `value == null ? d : value` | Yes | Yes | No | ||
| Default parameter `(v = d)` | Yes | No | No | ||
| Destructuring default `{ v = d }` | Yes | No | No |
When || Is the Right Choice
|| is not a mistake in itself. It is correct when every falsy value really should be replaced. Some common cases:
// Blank or whitespace-only input should show a placeholder.
const rawName = " ";
const displayName = rawName.trim() || "Anonymous";
console.log(displayName); // "Anonymous"
// An empty error message is no better than none.
const err = { message: "" };
console.log(err.message || "Unknown error"); // "Unknown error"
// A count of 0 retries makes no sense in this API, so treat it as unset.
const config = { retries: 0 };
const retries = config.retries || 3;
console.log(retries); // 3In each of these, the falsy value carries no useful meaning, so replacing it is the behavior you want. Before you write ||, ask: "If this value were 0, "" or false, would I want the fallback?" If the answer is yes for every falsy value the variable can hold, use ||. If not, use a check for missing values.
Chained Fallbacks
Because || returns the first truthy operand, you can chain several sources together:
const cliArgs = { port: undefined };
const envVars = { PORT: "" };
const fileConfig = { port: 8080 };
const port = cliArgs.port || envVars.PORT || fileConfig.port || 3000;
console.log(port); // 8080Evaluation runs left to right and stops at the first truthy value, so later sources are never read once one succeeds. Here the empty PORT string was skipped, which is probably what you want for environment variables. The same chain would also skip a deliberate port: 0, though. Before chaining, check that every link has the same meaning of "empty."
Debugging Checklist
When a default seems to override a value the user set, check these in order:
- Find every
||that touches the variable along its path from input to use. - List the falsy values that variable can legally hold:
0,"",false,NaN. - Look for
x || true, which can never producefalse. - Check whether data from JSON or a database uses
nullwhere your default parameters expectundefined. - Replace the check with one that tests for the missing state you actually mean.
Exercise
What does each line log? console.log(0 || 10); console.log("" || "x"); console.log(false || false); console.log(null || 0 || "");
Show answer
10, then "x", then false, then "". In the last line every operand is falsy, so || returns the final operand, the empty string.
Exercise
A function applyDiscount(price, discount) uses const d = discount || 0.1;. A customer with a negotiated 0% discount is still charged 10% less. Rewrite the line so that only a missing discount (undefined or null) falls back to 0.1, without using ??.
Show answer
const d = discount == null ? 0.1 : discount; (or discount === undefined || discount === null ? 0.1 : discount). A discount of 0 is now kept, and only undefined or null falls back.
Exercise
Why can options.darkMode || true never evaluate to false, and what does setTheme(null) return if the function is declared as function setTheme(mode = "light") { return mode; }?
Show answer
If darkMode is truthy, its own value is returned. If it is falsy, true is returned. Either way the result is truthy. setTheme(null) returns null, because default parameters apply only when the argument is undefined.