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
breakorcontinue. Areturninside the callback only skips to the next item. To stop early usefor...of,some,everyorfind. - Returns
undefined, so it cannot be chained. If you want a new array, usemaporfilter. - Ignores async.
items.forEach(async item => await save(item))fires all saves at once and continues immediately; errors become unhandled rejections. Usefor...ofwithawaitfor sequential work, orPromise.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
1const cart = [2 { name: "Book", qty: 2 },3 { name: "Pen", qty: 0 },4 { name: "Lamp", qty: 1 },5];67cart.forEach((item, i) => console.log(`${i + 1}. ${item.name} x${item.qty}`));89const result = cart.forEach(() => {});10console.log(result); // undefined - cannot chain1112// return only skips the current item; it does not stop the loop13cart.forEach((item) => {14 if (item.qty === 0) return;15 console.log("in stock:", item.name); // Book, Lamp16});1718// The async trap19const 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 awaited2324// Do this instead25for (const item of cart) await save(item); // sequential26const saved = await Promise.all(cart.map(save)); // parallel27console.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.