Array.prototype.forEach()
The one iteration method that produces nothing. Its two real limitations — no return value and no way to break — are exactly why for...of often reads better.
Demo
Every case returns undefined, and that is the whole lesson — no matter what the callback does or what it returns, forEach produces nothing. The work happens entirely through side effects. This is why `const result = items.forEach(...)` is always a bug, and why you cannot chain .filter() or .join() onto the end of a forEach.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(element, index, array). Its return value is ignored entirely. |
| thisArg | any | no (undefined) | Value of `this` inside the callback. Ignored for arrow functions. |
Return value
undefined — Always undefined — whatever the callback returns is discarded. Nothing can be chained onto it.
Common patterns
items.forEach(x => console.log(x));
for (const x of items) { if (found(x)) break; }
const doubled = items.map(x => x * 2);
Examples
Pitfalls
items.forEach(x => { if (found) return; check(x); });
for (const x of items) { if (found) break; check(x); }
const doubled = items.forEach(x => x * 2);
const doubled = items.map(x => x * 2);
items.forEach(async x => { await save(x); }); done();
for (const x of items) { await save(x); } done();
let n = 0; new Array(3).forEach(() => n++); n
new Array(3).fill(0).forEach(() => n++);
When to use
- Side effects only — logging, sending, mutating something external
- When the array is small and you will never need to stop early
- You want a value back → map, filter or reduce
- You might need to stop early → for...of with break
- The callback is async → for...of with await
- The array is sparse → fill it first, or use a for loop
Notes
FAQ
You cannot. return acts as continue, and there is no break. If you need early exit, use for...of with break — or some/every, which short-circuit by design, though they read as questions rather than loops.
for (const x of items) { if (done) break; }