← back

Don't get confused between map() and forEach()

Cover Image for Don't get confused between map() and forEach()

Don't get confused between map() and forEach()

JavaScript is the one of the easiest langauge to learn and as well as the most confusing langauge ever.

I have been using JavaScript for more than 2 years and I have missed out of a fair share of features, misunderstood a lot of things.

One of the most common mistakes I have seen is people (including me) using map() and forEach() wrong.

Now JavaScript offers us two methods to iterate over an array, map() and forEach().

Let's see what MDN documentation says about them.

The Array.prototype.forEach() method executes a provided function once for each array element.

What this means ?

The function that is passed as a parameter to the forEach() method will be executed for each element in the array.

The Array.prototype.map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

What this means ?

The function that is passed as a parameter to the map() method will be executed for each element in the array and the return value of the function will be added to the new array which will be returned by the map().

whoa thats a lot to consume, let's break it down.

forEach()

forEach() is a method that is used to iterate over an array and execute a function for each element in the array.

Let's see an example.

In the above code, we can see that a anoymous function (arrow functions) is passed as a parameter to the forEach() method. However, instead of returning a new array like map, it returns undefined.

map()

map() is a method that is used to iterate over an array and execute a function for each element in the array and return a new array.

Let's see one more example.

In the above code, we can see that a anoymous function is passed as a parameter to the map() method. This method will return a new array which we are using to print the values back to the console.

Any other differences ?

If you have heard the concept of chaining in JavaScript, then you might have heard of the term method chaining.

bascially in a nutshell method chaining is a way to call multiple methods on the same object.

You cannot attach multiple methods with forEach() as it returns undefined.

But you can chain many methods such as filter(), map(), reduce() etc with map() as it returns array.

Smol example code to see method chaining.

Which of em is speed ???

Both of em are equally speed, but I have seen people saying map() is more performant than forEach().

But ultimatetly it depends on the situation,

If you plan to use the returned array then use map() or else; just use forEach().

Smol Table for better Conclusion

forEach() map()
Iterates over an array Iterates over an array
Does not return anything Returns a new array
Cannot chain methods Can chain methods