What is forEach()?

forEach() calls a function once for every element of an array, purely for side effects; it always returns undefined, cannot be stopped early and does not wait for promises.

Signature

array.forEach((element, index, array) => { ... }, thisArg?)

Good uses

Logging, updating external state, adding DOM nodes, sending analytics events: anything where you do something per item rather than produce a new value.

Limitations

  • No break or continue. A return inside the callback only skips to the next item. To stop early use for...of, some, every or find.
  • Returns undefined, so it cannot be chained. If you want a new array, use map or filter.
  • Ignores async. items.forEach(async item => await save(item)) fires all saves at once and continues immediately; errors become unhandled rejections. Use for...of with await for sequential work, or Promise.all(items.map(...)) for parallel.
  • Skips holes in sparse arrays.
  • Changing the array while iterating (adding or removing items) leads to confusing behaviour.

forEach vs for...of

for...of is just as readable, supports break, continue and await, and works on any iterable (Map, Set, strings, generators). Many style guides now prefer it for side-effect loops. forEach remains handy in short chains like map.forEach((value, key) => ...).

Code example

js
1const cart = [
2 { name: "Book", qty: 2 },
3 { name: "Pen", qty: 0 },
4 { name: "Lamp", qty: 1 },
5];
6
7cart.forEach((item, i) => console.log(`${i + 1}. ${item.name} x${item.qty}`));
8
9const result = cart.forEach(() => {});
10console.log(result); // undefined - cannot chain
11
12// return only skips the current item; it does not stop the loop
13cart.forEach((item) => {
14 if (item.qty === 0) return;
15 console.log("in stock:", item.name); // Book, Lamp
16});
17
18// The async trap
19const save = (item) => new Promise((r) => setTimeout(() => r(item.name), 20));
20const started = [];
21cart.forEach(async (item) => started.push(await save(item)));
22console.log("after forEach:", started.length); // 0 - nothing was awaited
23
24// Do this instead
25for (const item of cart) await save(item); // sequential
26const saved = await Promise.all(cart.map(save)); // parallel
27console.log(saved); // ["Book", "Pen", "Lamp"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app