Syntax
arr.forEach((item, index, array) => { });Examples
Basic forEach()
Running a function for each element, purely for its side effects.
const fruits = ["apple", "banana", "cherry"];
fruits.forEach(fruit => {
console.log(fruit);
});
// apple, banana, cherryUsing Index and Array Parameters
The callback also receives the current index and the full array.
const scores = [85, 92, 78];
scores.forEach((score, index, array) => {
console.log(`Score ${index + 1} of ${array.length}: ${score}`);
});
// Score 1 of 3: 85
// Score 2 of 3: 92
// Score 3 of 3: 78forEach() vs map() - Choosing the Right Tool
A common mistake: using forEach() when you actually need a new array.
// Wrong intent - forEach() returns undefined, this does nothing useful
const numbers = [1, 2, 3];
const result = numbers.forEach(n => n * 2);
console.log(result); // undefined
// Correct - use map() when you need the transformed values back
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]Best practices
- Use forEach() only for side effects (logging, DOM updates, pushing to an external array) - never expect a return value from it
- Use map() instead of forEach() whenever you actually need a transformed array back
- Remember you cannot break or continue out of a forEach() loop - use a regular for or for...of loop if you need that control
- Avoid using forEach() with async/await callbacks expecting sequential execution - it does not wait for promises between iterations
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification