Sub topic 13
Early Returns and Guard Clauses
This chapter assumes you know how return works and that a function without one returns undefined. Here the focus is on where you place return statements to keep a function's logic flat and easy to read.
The Problem with Nested Conditions
When a function has to check several conditions before doing its real work, the checks often end up nested inside each other:
function shippingCost(order) {
if (order) {
if (order.items.length > 0) {
if (!order.freeShipping) {
return order.weight * 1.5;
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
}
console.log(shippingCost({ items: [1], weight: 4, freeShipping: false })); // 6The main calculation sits three levels deep, and each else is far from the if it belongs to.
Guard Clauses
A guard clause is a check at the top of a function that returns right away when a special case applies. return exits the function immediately, so nothing after it runs. That means you don't need an else:
function shippingCost(order) {
if (!order) return 0;
if (order.items.length === 0) return 0;
if (order.freeShipping) return 0;
return order.weight * 1.5;
}
console.log(shippingCost(null)); // 0
console.log(shippingCost({ items: [], weight: 4 })); // 0
console.log(shippingCost({ items: [1], weight: 4, freeShipping: false })); // 6Each guard handles one case and gets it out of the way. The last line is the normal path, and it is not indented at all.
Guards That Throw
A guard can also reject input that makes no sense. In that case you throw an error instead of returning a value:
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("divide expects two numbers");
}
if (b === 0) return Infinity;
return a / b;
}
console.log(divide(10, 4)); // 2.5
console.log(divide(1, 0)); // InfinityCommon Mistakes
- Mixing return types by accident. If some guards return
0and one returns nothing (a barereturn;), callers getundefinedfor that case. Make every exit return the same kind of value. - Placing guards after side effects. Run checks before you modify data, log, or make network calls. Otherwise a rejected call has already done part of its work.
- Burying the main path. Guards belong at the top. If an early return turns up halfway through a long function, consider splitting that function into smaller ones.
Exercise
Rewrite this function using guard clauses: function grade(score) { if (score >= 0 && score <= 100) { if (score >= 50) { return "pass"; } else { return "fail"; } } else { return "invalid"; } }
Show answer
function grade(score) { if (score < 0 || score > 100) return "invalid"; if (score < 50) return "fail"; return "pass"; } The out-of-range check comes first, then the failing case, and the common result is the final line.
Exercise
A function starts with if (!items) return; and ends with return items.length;. What does calling it with no argument return, and why might that cause trouble?
Show answer
It returns undefined, because a bare return gives undefined. A caller that expects a number could produce NaN in later arithmetic. Returning 0 in the guard keeps the return type consistent.