DEV Community

Ralph Virtucio
Ralph Virtucio

Posted on

forEach or map ?

Top comments (6)

jordienr profile image
Jordi Enric

Very easy, if you need to return an array, use map. Otherwise forEach.

jwp profile image
John Peters

Both iterate over the collection, one returns values the other doesn't. There's no difference in the iteration part.

People like to make rules on when to use them but I use map, and reduce way more than any other method regardless of mutability. Mutability is a choice of what we do with the data, not the function's themselves. We can choose to mutate or not using just map.

ifarmgolems profile image
Patrik Jajcay

Map for immutable new array, forEach for mutations / side effects.

notrab profile image
Jamie Barton

Like others have said, they both do very different things. If you don't need to return an array, use forEach :)

ralphvirtucio_ profile image
Ralph Virtucio

Thank you so much for your opinions !

atlasoss profile image

Depends on the usecase. I like map.