**forEach** iterates over an array and runs a callback for each element. Unlike **map**, it does not return a new array — it's purely for **side effects** (logging, updating external state). It cannot be broken early (use `for...of` with `break` if early exit is needed).
1Understanding Array.forEach()
forEach iterates over an array and runs a callback for each element. Unlike map, it does not return a new array — it's purely for side effects (logging, updating external state). It cannot be broken early (use for...of with break if early exit is needed).
If you need a return value, use map(). If you need early exit, use for...of. forEach is only for side effects.
const items = ['pen', 'paper', 'eraser'];
// Side effect: logging
items.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
// forEach returns undefined (not chainable)
const result = items.forEach(x => x.toUpperCase());
console.log(result); // undefined2Practical Example
Here is a real-world application of Array.forEach() showing how it is used in production JavaScript code.
// Async forEach pitfall
const ids = [1, 2, 3];
// WRONG: forEach doesn't await
ids.forEach(async (id) => {
await fetch('/api/' + id); // these run in parallel!
});
// CORRECT: use for...of
for (const id of ids) {
await fetch('/api/' + id); // sequential
}3Best Practices
Follow these guidelines when working with Array.forEach():
1. Use forEach only for side effects, not transformations
2. Use for...of when you need break or continue
3. Avoid async forEach — use for...of with await instead
Tip: If you need a return value, use map(). If you need early exit, use for...of. forEach is only for side effects.
const items = ['pen', 'paper', 'eraser'];
// Side effect: logging
items.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
// forEach returns undefined (not chainable)
const result = items.forEach(x => x.toUpperCase());
console.log(result); // undefined