When Loops Are Actually Clearer
You'll learn: When to choose a traditional for loop over functional patterns like reduce() or recursion for better readability.
The Core Idea
Functional programming patterns are powerful, but they're not always the clearest choice. Sometimes a straightforward for loop communicates your intent more directly than a complex reduce() chain or recursive function. Clarity beats cleverness.
When Loops Win
Multiple Accumulators or Complex State
If you're tracking several values simultaneously, reduce() becomes awkward:
// Reduce version: harder to follow
const result = items.reduce((acc, item) => {
acc.sum += item.value;
acc.count += 1;
acc.max = Math.max(acc.max, item.value);
return acc;
}, { sum: 0, count: 0, max: -Infinity });
// Loop version: clearer intent
let sum = 0;
let count = 0;
let max = -Infinity;
for (const item of items) {
sum += item.value;
count += 1;
max = Math.max(max, item.value);
}
Early Exit Logic
Loops naturally support break, making search operations obvious:
// Clear and efficient
let found = null;
for (const item of items) {
if (item.id === targetId) {
found = item;
break;
}
}
Forcing this into reduce() or recursion requires workarounds that obscure the logic.
Processing Interdependent Steps
When each iteration depends on complex state from previous iterations, loops keep the flow linear and readable.
The Guideline
Use functional patterns for transformation pipelines. Use loops when managing multiple variables, early exits, or complex iteration logic. Your teammates shouldn't need to mentally "decode" what the code does.
Key Takeaway: A simple loop that's immediately understandable beats a clever functional pattern that requires careful study—readability is a feature, not a weakness.