Replace conditionals with early returns to flatten code
early return pattern, guard clauses, else removal, arrow anti-pattern, nested conditional flattening
Early Returns: Eliminating Nested Conditionals
Deeply nested conditions are one of the most common readability problems in real code. The early return pattern — also called guard clauses — flattens them without changing logic.
The rule: check for invalid states first and return immediately. The happy path then runs at the lowest indentation level without any else branches.
// Before — pyramid of doom
function processPayment(user, amount) {
if (user) {
if (user.isActive) {
if (amount > 0) {
if (amount <= user.balance) {
return makePayment(user, amount);
}
}
}
}
return null;
}Refactored with guard clauses:
function processPayment(user, amount) {
if (!user) return null;
if (!user.isActive) return null;
if (amount <= 0) return null;
if (amount > user.balance) return null;
return makePayment(user, amount);
}The logic is identical. But now the failure cases are explicitly handled at the top, one per line, and the success path is immediately clear. This function now reads like a checklist.
Early returns don't just reduce nesting — they force you to think about each failure case explicitly. When a case needs different behavior (returning an error code vs returning null), each guard clause can handle it independently without an else-if chain.
Some style guides mandate a single return per function. Ignore that for readability. Multiple early returns make complex validation logic dramatically clearer, and modern debuggers have no trouble tracing them.
