Sub topic 13
Guard Patterns and Common Pitfalls in Real Code
This chapter assumes you already know the falsy values, how && and || return one of their operands, how short-circuit evaluation works, and how ?? and ?. behave. Here we use those rules in real code. A guard is a check that stops code from running, or picks a safe value, when data is missing or invalid. Most bugs in guards come from the same mistake: the code tests truthiness when the real question is narrower, such as "is this missing?" or "is this list empty?"
The Main Guard Patterns
Real code uses guards in a few recurring shapes. Each one depends on a truthiness rule you already know.
| Pattern | Example | What it relies on |
|---|---|---|
| Early return | `if (!user) return;` | `!` turns a falsy value into `true` |
| Conditional call | `isDebug && log(msg)` | `&&` skips the right side when the left is falsy |
| Fallback value | `name ?? "Guest"` | `??` replaces only `null` and `undefined` |
| Safe access | `user?.address?.city` | `?.` stops at `null` or `undefined` |
| Conditional value | `count > 0 && label` | `&&` returns the right operand when the left is truthy |
Each shape is fine on its own. The bugs show up when the test inside the guard is looser than the condition you actually meant.
Pitfall 1: `&&` Leaks a Falsy Operand
When && stops early, it returns the falsy left operand itself, not false. If that operand is 0, the 0 ends up in your output. UI code hits this often, because templates and rendering libraries print numbers but skip false, null and undefined.
function renderCount(items) {
return `<p>${items.length && `${items.length} items`}</p>`;
}
console.log(renderCount([])); // <p>0</p>
console.log(renderCount([1, 2])); // <p>2 items</p>
function renderCountSafe(items) {
return `<p>${items.length > 0 ? `${items.length} items` : ""}</p>`;
}
console.log(renderCountSafe([])); // <p></p>
console.log(renderCountSafe([1, 2])); // <p>2 items</p>The fix is to make the left operand a real boolean. You can do that with a comparison (items.length > 0), with !!items.length, or with a ternary that names both branches. When the result will be displayed, a ternary is the clearest choice because it states what to show in each case.
Pitfall 2: Truthiness Checks on Containers
Every object is truthy, and that includes empty arrays and empty objects. So a check like if (results) answers "does this variable hold an object?" It does not answer "is there anything in it?"
const results = [];
const filters = {};
if (results) console.log("results is truthy, even though it is empty");
if (filters) console.log("filters is truthy, even though it has no keys");
const hasResults = Array.isArray(results) && results.length > 0;
const hasFilters = filters != null && Object.keys(filters).length > 0;
console.log(hasResults, hasFilters); // false falseDecide which question you mean. If the value could be null or missing, check for that. If the value could be empty, check its size. Often you need both checks, joined with &&, so that the size check only runs once you know the value exists.
Pitfall 3: Valid Zeros and Empty Strings
A guard such as if (!value) treats 0, "" and false the same as "missing". That is wrong whenever those values are legitimate data. Examples include a quantity of 0, a discount of 0, a page index of 0, or a field the user deliberately cleared.
function describeStock(product) {
if (!product.stock) return "Stock unknown";
return `${product.stock} in stock`;
}
console.log(describeStock({ stock: 0 })); // "Stock unknown" (wrong)
console.log(describeStock({})); // "Stock unknown"
function describeStockFixed(product) {
if (product.stock == null) return "Stock unknown";
return `${product.stock} in stock`;
}
console.log(describeStockFixed({ stock: 0 })); // "0 in stock"
console.log(describeStockFixed({})); // "Stock unknown"The check x == null is a deliberate use of loose equality. It is true only for null and undefined, so it is the statement form of what ?? does in expressions. Many style guides allow == null as their one exception to "always use ===". If your team prefers to avoid it, write x === null || x === undefined.
Pitfall 4: Default Parameters Are Not `??`
Default parameter values apply only when the argument is undefined. An explicit null gets through. Neither default parameters nor ?? replace 0 or "", which is usually what you want. || replaces both, which usually is not.
function withDefaultParam(port = 8080) {
return port;
}
function withNullish(port) {
return port ?? 8080;
}
function withOr(port) {
return port || 8080;
}
for (const input of [undefined, null, 0]) {
console.log(input, withDefaultParam(input), withNullish(input), withOr(input));
}
// undefined 8080 8080 8080
// null null 8080 8080
// 0 0 0 8080Data from JSON APIs and databases often uses null for "no value". If your function receives that kind of data, a default parameter alone will let null through. Use ?? fallback inside the function body, or combine both: function f(port = 8080) { port ??= 8080; ... }.
Pitfall 5: Strings That Look Empty
" " is truthy, because only the zero-length string is falsy. Form input often contains nothing but whitespace, so if (name) accepts a name made of spaces.
function greet(rawName) {
const name = typeof rawName === "string" ? rawName.trim() : "";
return name ? `Hello, ${name}` : "Hello, guest";
}
console.log(greet(" Ada ")); // "Hello, Ada"
console.log(greet(" ")); // "Hello, guest"
console.log(greet(null)); // "Hello, guest"Normalize the value first, then test its truthiness. Once you have trimmed a string, a truthiness check really does mean "has visible content".
Pitfall 6: Hidden Side Effects in `&&` Chains
isDebug && console.log(msg) works, but it is an expression statement whose result nobody uses. Linters flag it with rules such as ESLint's no-unused-expressions, and readers can easily miss the side effect. When the goal is to run code, use an if statement. Keep && and || for producing values.
Calling an optional callback is a related case. onDone?.() skips the call only when onDone is null or undefined. If a caller passes some other non-function value, such as true, the call still throws a TypeError. When input comes from outside your code, a typeof check is stricter:
function finish(onDone) {
if (typeof onDone === "function") {
onDone("done");
}
}
finish((msg) => console.log(msg)); // logs "done"
finish(undefined); // no call
finish(true); // no call and no TypeErrorUse ?.() when your own code guarantees the value is either a function or nullish. Use typeof at trust boundaries, where you cannot make that guarantee.
Choosing the Right Check
A plain truthiness check is still the right tool when every falsy value really does mean "skip this". A DOM lookup that returns an element or null is one example. An optional object that is either present or undefined is another. In those cases if (el) is short and correct.
A Combined Example
The function below reads a nested config object. It uses each guard only where that guard matches the intent.
function buildRequest(config) {
if (config == null) {
throw new TypeError("config is required");
}
const retries = config.retry?.count ?? 3; // 0 is a valid retry count
const timeout = config.timeoutMs ?? 5000; // 0 means "no timeout"
const tags = Array.isArray(config.tags) ? config.tags : [];
const label = config.label?.trim() || "untitled"; // blank labels fall back
return {
retries,
timeout,
tags,
label,
hasTags: tags.length > 0,
};
}
console.log(buildRequest({ retry: { count: 0 }, timeoutMs: 0, label: " " }));
// { retries: 0, timeout: 0, tags: [], label: 'untitled', hasTags: false }The label line uses || on purpose. After trimming, an empty string is not valid data for this field, so falling back on any falsy value is correct. The same operator would be a bug on the retries line.
Exercise
const badge = user.unread && \${user.unread} new\; shows "0" on screen when there are no unread messages. Explain why and give two fixes.
Show answer
When user.unread is 0, && short-circuits and returns its left operand, the number 0, and the template prints it. Fix it by making the left side a boolean, as in user.unread > 0 && \${user.unread} new\`, or by using a ternary that returns an empty string: user.unread > 0 ? \${user.unread} new\ : ""`.
Exercise
What does function f(size = 10) { return size; } return for f(null), f(undefined) and f(0)? How would you make null also fall back to 10 without losing 0?
Show answer
It returns null, 10 and 0, because default parameters apply only to undefined. To also handle null, add size ??= 10; in the body, or return size ?? 10. Both keep 0 because ?? replaces only null and undefined.
Exercise
A function checks if (!list) return "No items"; before rendering list. Callers sometimes pass null and sometimes pass []. What goes wrong, and what is a correct guard?
Show answer
[] is truthy, so an empty array skips the guard and the function renders an empty list instead of "No items". A correct guard is if (!Array.isArray(list) || list.length === 0) return "No items";, which handles null, undefined, non-arrays and empty arrays.