Difference between .map() and .forEach() in JavaScript
Aabhas Saxena
IITian | Co - Founder Khabri Bai | Education was my escape from poverty, and it can be yours too ?? | Let's stay in touch, and navigate our paths side by side ??
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
In reality both .map() and .forEach() take 3 arguments:
Look at how to Use .map() first
As we can see above since we did not use return so undefined was returned in the mapSampleArray2.
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.
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()
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
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()