Sub topic 15
Cleaner Control Flow: Guard Clauses and Lookup Tables
The earlier chapters covered each control-flow construct separately. This chapter covers how to combine them so the code stays easy to read. Two patterns do most of that work. Guard clauses handle special cases first and leave the function early. Lookup tables swap long if/switch chains for data. The chapter ends with criteria for choosing the right construct.
This chapter assumes you already know if/else, switch, &&/||/??, for...of, continue, and the array methods find and some. All of these are covered earlier in the tutorial. You should also be comfortable with functions, objects, and early return.
The Problem: Nested Conditions
Here is a shipping-cost function written the way it often grows over time, one condition inside another:
function shippingCostNested(order) {
if (order) {
if (order.total < 100) {
if (order.method === "express") {
return 15;
} else if (order.method === "overnight") {
return 30;
} else {
return 5;
}
} else {
return 0;
}
} else {
return 0;
}
}
console.log(shippingCostNested({ total: 40, method: "express" })); // 15
console.log(shippingCostNested({ total: 150, method: "express" })); // 0
console.log(shippingCostNested(null)); // 0The function works, but it is hard to read for three reasons:
- The main logic, picking a rate, sits three levels deep.
- Each
elseis far from theifit belongs to. To learn why the function returns0at the bottom, you have to match braces. - Adding a fourth shipping method means editing control flow, not data.
Guard Clauses
A guard clause is an if near the top of a function that checks for a special or invalid case and returns (or throws) right away. Once the guards have run, the rest of the function can assume the input is valid. It no longer needs an else for those cases.
function shippingCostGuarded(order) {
if (!order) return 0; // guard: no order
if (order.total >= 100) return 0; // guard: free shipping
if (order.method === "express") return 15;
if (order.method === "overnight") return 30;
return 5;
}
console.log(shippingCostGuarded({ total: 40, method: "express" })); // 15
console.log(shippingCostGuarded({ total: 150, method: "express" })); // 0
console.log(shippingCostGuarded(undefined)); // 0Each special case now takes one line and sits next to its result. The code reads top to bottom with no matching braces to track. None of the else keywords are needed: once a branch has run return, the code after it only runs when that branch did not.
Guards That Throw
A guard can also reject bad input outright. This works well at trust boundaries, such as user input or API payloads:
function withdraw(account, amount) {
if (account == null) throw new TypeError("account is required");
if (typeof amount !== "number" || Number.isNaN(amount)) {
throw new TypeError("amount must be a number");
}
if (amount <= 0) throw new RangeError("amount must be positive");
if (amount > account.balance) throw new Error("insufficient funds");
account.balance -= amount;
return account.balance;
}
const acct = { balance: 50 };
console.log(withdraw(acct, 20)); // 30account == null is one of the few good uses of loose equality. It matches both null and undefined and nothing else.
Guards Inside Loops
Inside a loop, continue plays the role of a guard clause. Skip the items you don't want first, and keep the body of the loop flat:
const users = [
{ name: "Ada", active: true, email: "[email protected]" },
{ name: "Bo", active: false, email: "[email protected]" },
{ name: "Cy", active: true, email: "" },
];
for (const user of users) {
if (!user.active) continue;
if (!user.email) continue;
console.log(`Emailing ${user.name} at ${user.email}`);
}
// Emailing Ada at [email protected]When Guards Hurt
Guard clauses can be overdone. If a function has many exit points and also changes state between them, it becomes hard to tell what has happened by the time a given return runs. Keep guards at the top. Have them check conditions, not do work. If there are more than about five guards, the function is probably doing too much and should be split.
Lookup Tables
The three if statements that map order.method to a price are really data written as code. A lookup table stores that mapping in an object or Map and reads from it once:
const shippingRates = { standard: 5, express: 15, overnight: 30 };
function shippingCost(order) {
if (!order) return 0;
if (order.total >= 100) return 0;
return shippingRates[order.method] ?? shippingRates.standard;
}
console.log(shippingCost({ total: 40, method: "express" })); // 15
console.log(shippingCost({ total: 40, method: "drone" })); // 5Adding a method is now a one-line data change. The ?? operator supplies the default when the key is missing, and it does so without replacing a valid rate of 0. A || here would turn a free method ({ pickup: 0 }) into 5.
Gotcha: Inherited Keys
A plain object inherits properties from Object.prototype. If the key comes from outside your code, a lookup can return something you never put in the table:
const rates = { standard: 5, express: 15 };
console.log(rates["toString"] ?? rates.standard);
// [Function: toString] -- not a number!
console.log(rates["constructor"] ?? rates.standard);
// [Function: Object]There are three ways to fix this:
// 1. Check for an own property
const rate1 = Object.hasOwn(rates, "toString") ? rates["toString"] : rates.standard;
console.log(rate1); // 5
// 2. Use an object with no prototype
const safeRates = Object.assign(Object.create(null), { standard: 5, express: 15 });
console.log(safeRates["toString"] ?? safeRates.standard); // 5
// 3. Use a Map
const rateMap = new Map([
["standard", 5],
["express", 15],
]);
console.log(rateMap.get("toString") ?? rateMap.get("standard")); // 5A Map is the most explicit option. It also accepts keys of any type, including numbers, objects, and functions, and it never mixes your data with built-in properties.
Tables of Functions
A table value can be a function. This replaces a switch whose cases each do something different:
const operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => {
if (b === 0) throw new RangeError("division by zero");
return a / b;
},
};
function calculate(op, a, b) {
if (!Object.hasOwn(operations, op)) {
throw new Error(`Unknown operation: ${op}`);
}
return operations[op](a, b);
}
console.log(calculate("multiply", 6, 7)); // 42
console.log(calculate("divide", 9, 3)); // 3The guard and the table work together here. The guard rejects unknown operations, and the table picks the behavior.
Ranges Need an Ordered List
An object lookup only matches exact keys, so it cannot express a condition like score >= 90. For ranges, use an ordered array with find:
const gradeBands = [
{ min: 90, grade: "A" },
{ min: 80, grade: "B" },
{ min: 0, grade: "C or below" },
];
function grade(score) {
return gradeBands.find((band) => score >= band.min)?.grade ?? "invalid";
}
console.log(grade(85)); // "B"
console.log(grade(-5)); // "invalid"Order matters here just as it does in an if/else if chain. find returns the first band that matches, so the bands must be sorted from highest to lowest.
Choosing a Construct
| Situation | Best fit | Why |
|---|---|---|
| Missing or invalid input | Guard clause | Removes the special case before the main logic |
| Pick one of two values | `? :` | It is an expression, so the result can be assigned directly |
| Many exact keys mapped to data | Object, `Map` | Changes are data edits, and lookup reads it in one step |
| Many exact keys mapped to behavior | Table of functions | Replaces a large `switch` |
| Numeric ranges or thresholds | Ordered array + `find`, or `if`/`else if` | Order expresses the priority of the ranges |
| Few cases sharing code | `switch` with stacked `case` labels | Grouping cases is easy to see |
| Complex conditions over several variables | `if`/`else if` | Tables can't hold arbitrary boolean logic |
| Filtering or testing a collection | `filter`, `some`, `every` | Shows intent without a manual loop |
Lookup tables are not always better. With two or three cases, an if is often clearer than a table defined somewhere else in the file. Use a table when the mapping is long, changes often, or is shared by several functions.
Exercise
Rewrite this function using guard clauses and a Map-based lookup so that unknown roles return "none", a missing user returns "none", and a role named "constructor" also returns "none". function permission(user) { if (user) { if (user.role === "admin") { return "all"; } else if (user.role === "editor") { return "write"; } else if (user.role === "viewer") { return "read"; } else { return "none"; } } else { return "none"; } }
Show answer
const permissions = new Map([["admin", "all"], ["editor", "write"], ["viewer", "read"]]); function permission(user) { if (user == null) return "none"; return permissions.get(user.role) ?? "none"; } The guard handles a missing user. Map.get returns undefined for any key not stored in the Map, including "constructor", so ?? supplies "none".
Exercise
A teammate writes const limit = limits[plan] || 10; where limits = { free: 0, pro: 100 }. What does a free user get, and what are two problems with this line?
Show answer
A free user gets 10 instead of 0, because || replaces the falsy value 0. That is the first problem, and switching to ?? fixes it. The second problem is that plan comes from outside, so a value like "toString" returns an inherited function rather than a number. Check with Object.hasOwn(limits, plan) or store the limits in a Map.
Exercise
Why can't a plain object lookup replace if (temp < 0) return "freezing"; if (temp < 20) return "cool"; return "warm";, and what structure would you use instead?
Show answer
Object keys only match exact values, and these conditions are ranges. Use an ordered array such as [{ max: 0, label: "freezing" }, { max: 20, label: "cool" }, { max: Infinity, label: "warm" }] with bands.find((b) => temp < b.max).label. Keep the array sorted by max in ascending order so the first match is the correct one.