forEach() vs. map() — JavaScript Array Function Comparison

Foreach vs map cover

In this article, I'll compare the JavaScript array functions forEach and map. After reading this, you should know when to use which function and why.

Function overview

Array.map()

The map function iterates over a given array and returns the result:

let array = [1, 2, 3];
array = array.map((item) => {
  return item * 2;
});

console.log(array);
[2, 4, 6]

Array.forEach()

This function allows you to iterate over an array without returning an altered version of the array.

const array = [1, 2, 3];
array.forEach((item) => {
  item * 2; // effectively, this operation does nothing
});

console.log(array);
[1, 2, 3]

As you can see from the outputs, the use-cases for these two functions are totally different.

You will use map for changing each value of a given array, while forEach simplifies iterating over an array without changing its values.

Performance comparison of Array.forEach() and Array.map()

Do you want to know what the performance impacts are for these two functions?

A quick comparison on jsben.ch suggests that forEach is faster when iterating over an array that contains 1000000 numeric values.

// forEach benchmark code
array.forEach(item => item * 2);
// map benchmark code
array.map(item => item * 2);

Benchmark results forEach vs map - forEach wins this round

In this first test, forEach outperforms map.

However, if we want to keep the comparison fair, we'll have to get the same result for both benchmarks.

Remember, map returnes an altered version of the original array. In this case, it multiplies each value with 2.

To achieve the same with the forEach function, we'd have to create a new array to which we push each result:

// forEach benchmark code
const result = [];
array.forEach(item => result.push(item * 2));
// map benchmark code
array.map(item => item * 2);

Benchmark results forEach vs map - now, map wins

A fairer comparison results in map winning over forEach.

The measurements are more realistic now because the result of the code is comparable.

Which one should you use?

Having the performance benchmarks in mind, you should use the function that suits your use case the best.

Do you want to change each value of the array? Use map.

Do you want to do other operations for each of the values of a given array? Use forEach.

It doesn't make sense to use map if you don't want to change the array, and forEach if you want to change each value. As we saw, performance will suffer and the readability of your code as well.

Conclusion

I hope this short article was able to clarify the difference between those array functions. If you want to get more articles like this one, please leave me a comment and subscribe to my email newsletter.

Further reading