.map vs .forEach – what's the difference?

,

Another thing that I realised later than I probably should have was:

Why do .map and .forEach even both exist ?

In my mind they were both just useful when wanting to iterate over every single item inside an Array with no easy ability to stop in between 🛑.

But one day while working with react code I finally understood why you always saw .map being used in react code when iterating over items.

.map always returns something to a new Array, while .forEach does not return anything.

So when wanting to render React components for each item in an Array .map is used, because what you are getting at the end is an array of Components. And React natively can work with arrays of components and render them.

If you were to just use .forEach that would not work, because React is not getting anything passed back to it.

const prices = [ 10, 20 ];

let pricesWithDollar = prices.map( price => price + " $");
// pricesWithDollar is [ "10 $",'20 $' ]

let pricesWithDollar = prices.forEach( price => price + " $");
// pricesWithDollar is undefined

And with understanding that, the name forEach really makes even more sense. Because .forEach is used whenever you want to have something happen for each item.

Leave a Reply

Your email address will not be published. Required fields are marked *