Skip to content

Array ForEach Method

forEach() calls a function once for each element of an array, in order. The function, called a callback, receives three arguments: the element, its index and the array itself. Use forEach() when you want to do something with each element, such as print it or send it somewhere, and do not need a result back.

const tasks = ['Buy milk', 'Post the parcel', 'Book the dentist'];
tasks.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});

This prints:

1. Buy milk
2. Post the parcel
3. Book the dentist

forEach() always returns undefined, so it cannot build a new array for you. Assigning a new value to the callback’s parameter does not change the array either, because the parameter holds a copy of the element’s value.

const prices = [4.5, 12, 7.25];
const result = prices.forEach((price) => {
price = price * 2;
});
console.log(result);
console.log(prices);

This prints:

undefined
[ 4.5, 12, 7.25 ]

To change the array in place, write to it through the index and the third argument:

const prices = [4.5, 12, 7.25];
prices.forEach((price, index, array) => {
array[index] = price * 2;
});
console.log(prices);

This prints:

[ 9, 24, 14.5 ]

When you want a new array of changed values and want to leave the original alone, map() is the better tool.

There is no way to break out of forEach() short of throwing an error. A return inside the callback only ends that one call, so the loop moves straight on to the next element.

const temperatures = [14, 17, 22, 19];
temperatures.forEach((temperature) => {
if (temperature > 20) return;
console.log(temperature);
});

This prints:

14
17
19

Where the loop should stop at the first match, use a for...of loop with break, or a method that stops by design, such as some(), every() or find().

const temperatures = [14, 17, 22, 19];
for (const temperature of temperatures) {
if (temperature > 20) break;
console.log(temperature);
}

This prints:

14
17

forEach() also skips the empty slots in a sparse array, such as the gap in [1, , 3], whereas a for...of loop visits them as undefined.

Steve Griffith covers this topic in his video JavaScript Array forEach Method.