DEV Community

Discussion on: Stop using Array.map() everywhere 🥵

Collapse
 
matthewbdaly profile image
Matthew Daly

I disagree somewhat. While the correct use case for map() is for when you want to transform the items in an array, and you shouldn't use it if you're just carrying out an action on each item, these days loops (as opposed to the forEach() method) are best avoided for most use cases, particularly when using a UI library like React.

Using chainable array methods like map() and forEach() has numerous advantages over a loop:

  • It breaks your code into a series of steps, making it easier to understand and reason about than nested loops
  • Because the callback for each is a function, you can add type hints for the parameters and return value when using Flow or Typescript to help document what each item represents
  • It mitigates the need for multiple levels of indentation

Yes, if you're not changing the data, you should use forEach() rather than map(), but in code reviews I would actively discourage using a loop if you can use forEach() instead.

Some comments have been hidden by the post's author - find out more