Codectionary / Developer documentation / JavaScript

forEach()

forEach() executes a function once for each array element, used purely for side effects like logging or updating external state - it always returns undefined and cannot be chained. Unlike map()/filter(), it does not produce a new array, and unlike a for loop, it cannot be stopped early with break.

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, cherry

Using 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: 78

forEach() 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation