Difference between .map() and .forEach() in JavaScript

Difference between .map() and .forEach() in JavaScript

If we use a return keyword in .map() we can get the new array with the results of the function applied to each element else we get undefined. This will not change the original array unless we explicitly do so in the function that is passed to the map().

While forEach is just used to execute a function over every element of the array. This does not change the original array unless we explicitly do so in the function that is passed to the forEach(). Also this does not return anything even if we try to return using the return keyword.

Beginner Bonus Tip


3 arguments taken by .map() and .forEach()

In reality both .map() and .forEach() take 3 arguments:

  1. The data element of the array
  2. The data element index
  3. The original array on which we are applying the .map() or .forEach()

Look at how to Use .map() first

Using map without return

As we can see above since we did not use return so undefined was returned in the mapSampleArray2.


Using .map() with return keyword

Above is simple example of using .map() on sampleArray with the return keyword and returning the resultant new array called mapSampleArray. Our original array viz. sampleArray will not change here.


Changing original Array using .map()

Above we have explicitly changed the sampleArray. Also notice how sampleArray3 gets all values as undefined since we did not use the return keyword.

Now look at how to use .forEach()


Using .forEach() on a JavaScript Array

Here even after using return keyword the forEach() does not return anything and resulting array is undefined. Also see how original array viz. sampleArray did not change, however funtion inside forEach() was executed correctly as we can see from console.log


How to change original array using .forEach()

Here we clearly change the original array using the statements inside the function passed to .forEach.

Hope this clears every doubt on .forEach() and .map()


要查看或添加评论,请登录

社区洞察

其他会员也浏览了