Sub topic 15
Cleaner Control Flow: Guard Clauses and Lookup Tables
This chapter assumes you know if/else, switch, the ?? operator, and array methods such as filter and some from earlier chapters. The focus here is structure: how to arrange branches so a reader can follow them quickly.
Guard Clauses: Handle Special Cases First
Deep nesting happens when every check wraps the next one. The normal case ends up buried several levels in:
function discount(user) {
if (user) {
if (user.active) {
if (user.orders > 10) {
return 0.2;
} else {
return 0.05;
}
} else {
return 0;
}
} else {
return 0;
}
}
console.log(discount({ active: true, orders: 12 })); // 0.2A guard clause is an early return that deals with an invalid or special case at the top of a function. Once each guard has passed, the rest of the function can assume valid input:
function discount(user) {
if (!user) return 0;
if (!user.active) return 0;
if (user.orders > 10) return 0.2;
return 0.05;
}
console.log(discount(null)); // 0
console.log(discount({ active: true, orders: 3 })); // 0.05Each line reads as one rule, and the else keywords are gone because a return already ends the function. Guards also work inside loops, where continue plays the same role as return.
Lookup Tables: Replace Branches with Data
If a switch or an if chain does nothing except map one value to another, an object can hold that mapping. The code becomes a single property lookup, with ?? supplying the fallback:
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 new shipping method is now a data change, and you could load the table from configuration. The values in a table can also be functions when each case needs different behavior:
const handlers = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
};
function calc(op, a, b) {
const fn = handlers[op];
if (!fn) throw new Error(`Unknown op: ${op}`);
return fn(a, b);
}
console.log(calc("add", 2, 3)); // 5const rates = new Map([["standard", 5], ["express", 15]]);
console.log(rates.get("toString") ?? rates.get("standard")); // 5Choosing a Construct
| Situation | Clearest choice |
|---|---|
| Invalid input or an early exit | Guard clause |
| Picking between two values | Conditional operator |
| One value mapped to a result or action | Lookup table or `Map` |
| Several values sharing code, with side effects | `switch` |
| Conditions on ranges or several variables | `if`/`else if` chain |
| Filtering, transforming, or testing a collection | Array methods |
These are guidelines, not rules. Write the version a teammate will understand fastest.
Exercise
Rewrite this function using a guard clause and a lookup table: function label(code) { if (code === 200) { return "OK"; } else if (code === 404) { return "Not Found"; } else if (code === 500) { return "Server Error"; } else { return "Unknown"; } }. Also make sure label("constructor") returns "Unknown".
Show answer
const labels = new Map([[200, "OK"], [404, "Not Found"], [500, "Server Error"]]); function label(code) { if (!labels.has(code)) return "Unknown"; return labels.get(code); } A Map holds only the entries you add, so "constructor" is not found and the guard returns "Unknown". A plain object would return the inherited Object constructor function for that key.
Exercise
Why does a guard clause usually need no else after it?
Show answer
The guard ends with return (or continue, or throw), which leaves the function or iteration. Any code after the guard runs only when the guard's condition was false, so an else adds nothing except an extra level of nesting.