Sub topic 15
Early Returns and Guard Clauses
This chapter assumes you can declare and call functions and that you know a function returns undefined when it reaches its end without a return. That rule was covered in the previous chapter. Here the focus is on where you place return statements and why placing some of them at the top of a function makes the code easier to read.
What an Early Return Is
An early return is a return statement that ends the function before it reaches its last line. When JavaScript runs a return, the function stops at that point. No later statement in the function body runs, except for a finally block, which is covered below.
A guard clause is an early return placed at the top of a function. It checks for a special case, such as invalid input, an empty collection, or a value that needs no work, and handles that case at once. The code after the guards can then assume the input is in the normal, expected shape.
From Nested Conditions to Guards
Without early returns, each special case adds another level of if/else:
function shippingCost(order) {
if (order) {
if (order.items.length > 0) {
if (order.country === "US") {
return 5;
} else {
return 15;
}
} else {
return 0;
}
} else {
return 0;
}
}
console.log(shippingCost({ items: [1], country: "US" })); // 5To check what happens when order is missing, you have to match the last else back to the first if. Here is the same logic written with guard clauses:
function shippingCost(order) {
if (!order) return 0; // guard: no order
if (order.items.length === 0) return 0; // guard: nothing to ship
if (order.country === "US") return 5;
return 15;
}
console.log(shippingCost(null)); // 0
console.log(shippingCost({ items: [], country: "FR" })); // 0
console.log(shippingCost({ items: [1], country: "US" })); // 5
console.log(shippingCost({ items: [1], country: "FR" })); // 15Each condition and its result now sit on one line. The common case, an international order with items, is the last line and has no indentation.
Ordering Guards
The order of guards matters because later guards depend on what earlier ones ruled out. order.items.length is safe to read only because !order was checked first. If you swapped those two lines, shippingCost(null) would throw TypeError: Cannot read properties of null.
As a rule, put the cheapest and most basic checks first: existence, then type, then shape, then business rules.
Return or Throw?
A guard can either return a value or throw an error. Pick one based on what the special case means:
| Situation | Guard action | Example |
|---|---|---|
| Valid input that needs no work | Return a neutral value | Empty cart returns `0` |
| Caller broke the function's contract | Throw an error | A negative quantity |
| Optional lookup that found nothing | Return `null` or `undefined` | User ID not found |
function lineTotal(price, quantity) {
if (typeof price !== "number" || typeof quantity !== "number") {
throw new TypeError("price and quantity must be numbers");
}
if (quantity < 0) throw new RangeError("quantity cannot be negative");
if (quantity === 0) return 0;
return price * quantity;
}
console.log(lineTotal(2.5, 4)); // 10
console.log(lineTotal(2.5, 0)); // 0If a guard returns a quiet default for input that is actually a mistake, the bug shows up later, far from where it started.
Early Returns Inside Loops
return inside a loop ends the loop and the whole function. That makes it a direct way to stop searching once you find a match:
function firstAdult(people) {
for (const person of people) {
if (person.age >= 18) return person; // stop at the first match
}
return null; // reached only if nothing matched
}
console.log(firstAdult([{ age: 12 }, { age: 30 }, { age: 45 }])); // { age: 30 }
console.log(firstAdult([{ age: 9 }])); // nullThe final return null matters. Without it, a failed search would return undefined implicitly, and that is less clear about what it means.
Pitfall: return Inside a Callback
A return exits the innermost function that contains it. Inside a forEach callback, that function is the callback, not the outer function:
function hasNegative(nums) {
nums.forEach((n) => {
if (n < 0) return true; // exits the callback only
});
return false;
}
console.log(hasNegative([1, -2, 3])); // false (wrong)forEach ignores the callback's return value, so the outer function always reaches return false. You can fix this with a for...of loop, where return belongs to hasNegative, or with a method built for the job:
function hasNegativeLoop(nums) {
for (const n of nums) {
if (n < 0) return true;
}
return false;
}
const hasNegativeSome = (nums) => nums.some((n) => n < 0);
console.log(hasNegativeLoop([1, -2, 3])); // true
console.log(hasNegativeSome([1, -2, 3])); // truePitfall: A Guard Without return
A guard that logs a message but leaves out return lets execution continue into code that assumes valid input:
function initials(name) {
if (!name) {
console.log("No name given");
// missing return: execution continues
}
return name.split(" ").map((part) => part[0]).join("");
}
console.log(initials("Ada Lovelace")); // "AL"
// initials(""); // logs "No name given", then throws TypeError? No: "".split(" ") works and returns ""
// initials(undefined); // logs, then throws TypeError: Cannot read properties of undefinedEvery guard needs to end the function, either with return or with throw.
Early Returns and finally
When a return runs inside a try block, the finally block still runs before the function exits. This makes early returns safe in code that must release a resource:
function readValue(source) {
try {
if (!source) return "empty";
return source.value;
} finally {
console.log("cleanup ran");
}
}
console.log(readValue(null)); // logs "cleanup ran", then "empty"
console.log(readValue({ value: 7 })); // logs "cleanup ran", then 7When Not to Use Early Returns
Guards work best for preconditions, meaning checks about whether the main logic should run at all. If a function's branches are equally important alternatives, such as picking one of four formatting styles, a switch statement or a lookup object shows that choice more clearly than a series of returns. A long function with returns scattered through the middle is also hard to follow. In that case, split the function into smaller ones instead of adding more exits.
Exercise
Rewrite this function using guard clauses so that it has no else branches and no nesting deeper than one level: function grade(score) { if (typeof score === "number") { if (score >= 0 && score <= 100) { if (score >= 90) { return "A"; } else { return "B or below"; } } else { throw new RangeError("score out of range"); } } else { throw new TypeError("score must be a number"); } }
Show answer
function grade(score) { if (typeof score !== "number") throw new TypeError("score must be a number"); if (score < 0 || score > 100) throw new RangeError("score out of range"); if (score >= 90) return "A"; return "B or below"; } The type check comes first, so the range comparison only ever runs on numbers.
Exercise
What does findIndexOf([4, 8, 15], 8) return, and why? function findIndexOf(arr, target) { arr.forEach((value, i) => { if (value === target) return i; }); return -1; }
Show answer
It returns -1. The return i statement exits only the arrow callback, and forEach ignores the callback's return values. The outer function always reaches return -1. Use a for loop with return i inside it, or arr.indexOf(target).
Exercise
A function wraps its logic in try { if (!input) return "none"; return process(input); } finally { return "done"; }. What does it return when input is null, and what happens if process throws?
Show answer
It returns "done" in both cases. The return in finally overrides the guard's "none", and it also swallows the exception thrown by process, so the caller never sees the error.