iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

MethodReturnsUse it for
forEach(fn)undefined — side effects onlyDoing something with each item (logging, mutating external state).
map(fn)New array, one-to-oneTransforming each item.
filter(fn)New array, subsetKeeping items that match.
reduce(fn, init)Any single valueSum, group, build any structure.
flatMap(fn)New array, one-to-manyLike map, but flattens one level.
for…ofSequential 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, );

Test yourself

Q1. Inside a forEach callback you cannot…
Q2. Sum an array idiomatically with…
Q3. Run async work in parallel from an array with…

Discussion

Loading…