Hacker News new | ask | show | jobs
by scottmf 3086 days ago
Why use map instead of forEach?
1 comments

If you only want to translate(map) each element in to another set of value, using Map is much more simpler and readable than forEach
Actually, this is incorrect. You're abusing map here. The purpose of map is to map an existing array onto a new array. You're using map here to mutate properties on nodes in the original array, and creating a new Array, which has the length of the initial array, where each value is the return value of `node.style.background = 'yellow';`

forEach is much more indicative of what you're actually doing here, which is running through an iterable and mutating properties on each node.

Simple rule of thumb: if you're not using the results of `map`, you shouldn't be using it.

The code loops through an array, has side effects and returns nothing so forEach would be more descriptive IMO.

As for simple/readable it’s the same code but s/map/forEach.