Saturday, August 7, 2021

Difference between forEach() and map() methods?

 Ans:-

1. The returning value

The forEach() method returns undefined and map() returns a new array with the transformed elements. 

const myAwesomeArray = [1, 2, 3, 4, 5]

myAwesomeArray.forEach(x => x * x)

//>>>>>>>>>>>>>return value: undefined


myAwesomeArray.map(x => x * x)

//>>>>>>>>>>>>>return value: [1, 4, 9, 16, 25]


2. Ability to chain other methods

map() is chainable. This means that you can attach reduce(), sort(), filter() and so on after performing a map() method on an array.


That's something you can't do with forEach() because, as you might guess, it returns undefined.


const myAwesomeArray = [1, 2, 3, 4, 5]

myAwesomeArray.forEach(x => x * x).reduce((total, value) => total + value)

//>>>>>>>>>>>>> Uncaught TypeError: Cannot read property 'reduce' of undefined

myAwesomeArray.map(x => x * x).reduce((total, value) => total + value)

//>>>>>>>>>>>>>return value: 55

No comments:

Post a Comment