Sub topic 13
Guard Patterns and Common Pitfalls in Real Code
This chapter assumes you know which values are falsy, that && and || return one of their operands, and how ?? and ?. work. Here those pieces are put to work as guards. A guard is an expression or statement that stops code from running when a value is missing or unusable.
Common Guard Shapes
Real code mostly uses three shapes: the && guard, the early return, and the || or ?? fallback.
function notify(user, onSent) {
// Early return: stop the function when input is unusable
if (!user) return "no user";
// && guard: call only when a value is present
onSent && onSent(user.name);
// ?? fallback: supply a default only for null or undefined
const lang = user.lang ?? "en";
return `sent to ${user.name} in ${lang}`;
}
console.log(notify(null)); // "no user"
console.log(notify({ name: "Ana" })); // "sent to Ana in en"
console.log(notify({ name: "Bo", lang: "fr" }, (n) => console.log("ok", n)));
// logs "ok Bo", then "sent to Bo in fr"An early return keeps the rest of the function free of nested if blocks. An && guard works well for a single call made only for its side effect. When the guarded value might also be a non-function such as true, prefer onSent?.(). It skips only null and undefined, and it states the intent more clearly.
Pitfall 1: The Leaking 0
&& returns its first falsy operand. That operand is not always false.
const items = [];
const label = items.length && `${items.length} items`;
console.log(label); // 0, not false
const safeLabel = items.length > 0 && `${items.length} items`;
console.log(safeLabel); // falseThis causes trouble when the result is rendered. Many UI templates skip false, null and undefined but print 0. A user then sees a stray "0" on the page. Make the left side a real boolean with a comparison or with !! before you use && to render something.
Pitfall 2: Fallbacks That Erase Valid Data
|| replaces every falsy value, so legitimate 0, "" and false are lost.
function createPlayer(options) {
const volume = options.volume || 50; // bug: 0 becomes 50
const muted = options.muted ?? false; // correct: keeps false
const fixedVolume = options.volume ?? 50;
return { volume, fixedVolume, muted };
}
console.log(createPlayer({ volume: 0, muted: false }));
// { volume: 50, fixedVolume: 0, muted: false }Default parameters (function f(volume = 50)) behave differently from both operators. They apply only when the argument is undefined, and an explicit null passes through.
Pitfall 3: Guarding the Wrong Thing
A truthy check tells you a value exists. It does not tell you the value has the right type. The string "0" and the empty array [] both pass if (value). If you need a non-empty array, check Array.isArray(value) && value.length > 0.
Choosing a Guard
| Situation | Prefer | Column | Column |
|---|---|---|---|
| Value may be null or undefined, other falsy values are valid | `??` or `?.` | ||
| Any falsy value should be treated as missing | `\ | \ | ` or `if (!x)` |
| Result will be displayed | Explicit comparison, such as `n > 0 &&` | ||
| Whole function is meaningless without input | Early return |
Exercise
A cart component shows cart.count && "Items: " + cart.count. When the cart is empty, the page shows "0". Rewrite the expression so an empty cart produces false and a non-empty cart produces the label.
Show answer
Use cart.count > 0 && "Items: " + cart.count. The comparison returns a real boolean, so an empty cart gives false, which templates skip. A count of 0 no longer leaks through as the result of &&.
Exercise
What does ({ retries: 0 }).retries || 3 return, and how do you keep the 0?
Show answer
It returns 3, because 0 is falsy and || falls back to the right operand. Write ({ retries: 0 }).retries ?? 3 to get 0, since ?? falls back only for null or undefined.