Javascript Map vs. ForEach in Simple Language

forEach()

The forEach method executes a provided function once for each array element. ( Note- The function callback is allowed to completely change the calling array)

Let’s look at the code below:

var evenNum = [2, 4, 6];
evenNum.forEach((item, index) => {
 return evenNum[index] = item * 2.5;
});

console.log(evenNum);

// Expected Output [5, 10, 15]

.map()

Map method calls the provided function once for each element in an array in order and creates a new array from the result. ( Note- The function callback is not allowed to change the calling array )

Let’s look at the code below:

var evenNum = [2, 4, 6];
var doubles = evenNum.map((item) => {
 return item * 2.5;
});

console.log(evenNum);
// Expected Output [2, 4, 6]

console.log(doubles);
// Expected Output [5, 10, 15]

What’s the difference ?

forEach() changed the original array evenNum whereas map() returns a new array, without changing the array evenNum .

So, which one is better?

It depends, if you have to change array completely choose .forEach and if you just want to alter the data choose .map

Which one is faster?

if you go to the website jsbench.me, you’ll find out .map method is 60% faster than .forEach but it shouldn’t affect your application’s performance significantly.

Closing Notes:

1- forEach() allows to change the original array

2- map() doesn’t allows to change the original array but returns a new array of the same size.

3- map() is 60-80% faster.

I have another blog post, explaining the common Array methods in detail. If you are not familiar with them, you can read that to understand the other popular Array methods like filter() and reduce().

7 Amazing Array Methods to Boost your Javascript Skills Today

If you like this post and it was helpful, join me on Facebook 

Tanisk Jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.

Leave a Reply

Your email address will not be published. Required fields are marked *