I'm a professional PHP, Python and Javascript developer from the UK. I've worked with Django, Laravel, and React, among others. I also maintain a legacy Zend 1 application.
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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 theforEach()
method) are best avoided for most use cases, particularly when using a UI library like React.Using chainable array methods like
map()
andforEach()
has numerous advantages over a loop:Yes, if you're not changing the data, you should use
forEach()
rather thanmap()
, but in code reviews I would actively discourage using a loop if you can useforEach()
instead.