JS Array Iteration
"Iteration" methods run a callback for each item. The four big ones — forEach, map, filter, reduce — replace most loops in modern JS.
Which to pick
| Method | Returns | Use it for |
|---|---|---|
forEach(fn) | undefined — side effects only | Doing something with each item (logging, mutating external state). |
map(fn) | New array, one-to-one | Transforming each item. |
filter(fn) | New array, subset | Keeping items that match. |
reduce(fn, init) | Any single value | Sum, group, build any structure. |
flatMap(fn) | New array, one-to-many | Like map, but flattens one level. |
for…of | — | Sequential awaits, early break. |
reduce in three shapes
JS
// Sum
nums.reduce((total, n) => total + n, 0);
// Count occurrences
words.reduce((counts, w) => (counts[w] = (counts[w] || 0) + 1, counts), {});
// Group by a key
users.reduce((groups, u) => {
(groups[u.role] ||= []).push(u);
return groups;
}, {});
Async iteration
JS
// ❌ forEach with await does NOT wait — the callback returns a promise the array ignores
arr.forEach(async item => { await save(item); });
// ✓ Sequential — for…of awaits properly
for (const item of arr) {
await save(item);
}
// ✓ Parallel
await Promise.all(arr.map(item => save(item)));
Tip: Avoid index-based
for loops when you don't need the index. for…of and the iteration methods read better and avoid off-by-one bugs.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Array Iteration!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Sum an array of numbers with reduce.
const total = nums.reduce((t, n) => t + n,
);
The initial accumulator value.
Discussion
Loading…