Map Vs ForEach In Detailed

Spread the love

Are  you a beginner in Javascript? Confused about two  similar seemingly Array methods: Array.prototype.map() and Array.prototype.forEach()?

Here are the differences…

Definitions

map():

Map() method allows you to execute a call-back function to loop over an array easily.And it returns with the new array by not changing the source array. We can call this method as an immutable.

forEach():

ForEach() method allows you to execute a call back function by iterating through each element of an array. But the difference is it doesn’t return anything. If you try to return the value, you will get “undefined”. It will allows you to modify the source array by applying call back function. So, we can call this method as mutator.

Differences:

  1. The Return Methods: As you can see one of the main differences is the return of each method. The forEach() returns “undefined” where as map() returns new array with transformed elements.
  1. Ability to chain with other methods:  The second difference you can see is map() is chainable. You can chain with other methods like reduce(), sort(), filter() … after executing the map() method as it returns with new array. Whereas  you can’t chain forEach() with other method as it returns undefined.
  1. Mutability:   You already Know the map() returns an entirely new array by not chaining the source array. Were as even though it returns undefined in forEach() method, you can change or modify the source array by applying call back function. so, we call forEach() as Mutator method.
  1. Performance :Some posts mentions map() is faster than forEach(), and some other forEach () is faster than map().

when iterating over an array that contains 10000 numeric values forEach() is faster. However, if we want to keep the comparison fair, we’ll have to get the same result for both cases. 

Remember, map() returns an altered version of the original array. In this case, it multiplies each value with 2. To achieve the same with the forEach(), we’d have to create a new array to which we push each result. In this case map() is faster than forEach().

  1. What to Use ? You should choose the best that suits your case, by keeping the performance in mind.

If you would like to change each element of an Array use map().

If you want to loop through the elements of an array and don’t need a return array use forEach().

admin

admin

Leave a Reply

Your email address will not be published.