JavaScript: Difference between .forEach() and .map() JavaScript: Difference between .forEach() and .map() arrays arrays

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


They are not one and the same. Let me explain the difference.

forEach: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database) and does not return anything.

map: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although if passed a callback function, it may do so).

References

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN


  • Array.forEach “executes a provided function once per array element.”

  • Array.map “creates a new array with the results of calling a provided function on every element in this array.”

So, forEach doesn’t actually return anything. It just calls the function for each array element and then it’s done. So whatever you return within that called function is simply discarded.

On the other hand, map will similarly call the function for each array element but instead of discarding its return value, it will capture it and build a new array of those return values.

This also means that you could use map wherever you are using forEach but you still shouldn’t do that so you don’t collect the return values without any purpose. It’s just more efficient to not collect them if you don’t need them.


forEach()map()
FunctionalityPerforms given operation on each element of the arrayPerforms given "transformation" on a "copy" of each element
Return valueReturns undefinedReturns new array with transformed elements, leaving back original array unchanged.
Preferrable usage scenario and examplePerforming non-tranformation like processing on each element.

For example, saving all elements in the database.
Obtaining array containing output of some processing done on each element of the array.

For example, obtaining array of lengths of each string in the array

forEach() example

chars = ['Hello' , 'world!!!'] ;    var retVal = chars.forEach(function(word){  console.log("Saving to db: " + word) })  console.log(retVal) //undefined