Performance Considerations
You'll learn when multiple array passes are acceptable and when a single loop is more efficient.
Understanding Multiple Passes
Using map and filter together is wonderfully readable—each operation has a clear purpose. However, each method creates a brand new array and iterates through all elements. When you chain them, you're making multiple passes over your data:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Two passes: filter creates array, then map transforms it
const result = numbers
.filter(num => num % 2 === 0)
.map(num => num * 2);
// First pass: [2, 4, 6, 8, 10]
// Second pass: [4, 8, 12, 16, 20]
When Multiple Passes Are Fine
For small to medium datasets (hundreds or low thousands of items), the performance difference is negligible. Modern JavaScript engines optimize these operations well. The readability benefit usually outweighs the minor performance cost.
When to Consider a Single Loop
For large datasets or performance-critical code, a traditional loop can be more efficient:
// Single pass through the array
const result = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
result.push(numbers[i] * 2);
}
}
Think of it like a factory assembly line: map and filter create two separate stations where items pass through twice. A single loop is like combining both tasks at one station—items only pass through once.
The Practical Rule
Start with the readable approach (map, filter). Only optimize if profiling shows it's actually a bottleneck. Premature optimization often sacrifices clarity for unmeasurable gains.
Key Takeaway: Multiple array method passes are fine for most cases—readable code beats micro-optimizations unless you're working with large datasets or proven performance issues.