forEach() Method

forEach() calls a function once for each element in an array, in order. It is useful when you want to do something with each item but you do not need a new array back.

Syntax

array.forEach(function(currentValue, index, array) {
  // code to run for each element
});
  • currentValue: the current element.
  • index: the index of the current element (optional).
  • array: the original array (optional).

Basic example

Using a for loop:

const names = ['Anna', 'John', 'Peter'];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

Using forEach():

const names = ['Anna', 'John', 'Peter'];

names.forEach(function(name) {
  console.log(name);
});

Output:

Anna
John
Peter

With an arrow function

Arrow functions make forEach() more concise:

const names = ['Anna', 'John', 'Peter'];

names.forEach(name => console.log(name));

Accessing the index

const names = ['Anna', 'John', 'Peter'];

names.forEach((name, index) => {
  console.log(`${index}: ${name}`);
});
// 0: Anna
// 1: John
// 2: Peter

Updating elements in place

You can modify the original array inside forEach() using the index:

const names = ['Anna', 'John', 'Peter'];

names.forEach((item, index, arr) => {
  arr[index] = `Hello, ${item}`;
});

console.log(names); // ['Hello, Anna', 'Hello, John', 'Hello, Peter']

forEach() vs map()

This is one of the most common points of confusion between these two methods.

forEach()map()
ReturnsundefinedA new array
ChainableNoYes
Use whenYou want side effects (logging, DOM updates, API calls)You want to transform each item into a new value
// forEach: for side effects
['a', 'b', 'c'].forEach(letter => console.log(letter));

// map: for transformation
const upper = ['a', 'b', 'c'].map(letter => letter.toUpperCase());
console.log(upper); // ['A', 'B', 'C']

Common mistakes

Trying to break out of a forEach(). You cannot use break or continue inside forEach(). If you need to stop early, use a regular for loop or for...of instead.

Using forEach() when you want a new array. If you find yourself pushing items into a new array inside forEach(), that is a sign you should use map() or filter() instead.

// Avoid this pattern
const doubled = [];
[1, 2, 3].forEach(n => doubled.push(n * 2));

// Do this instead
const doubled = [1, 2, 3].map(n => n * 2);