DEV Community

Discussion on: Stop mutating in map, reduce and forEach

Collapse
 
hoffmann profile image
Peter Hoffmann

I understand your concerns and would like to propose something more idiomatic to modern javascript and the map function.

const newItems = items.map(i => { ...i, id: userId })
Enter fullscreen mode Exit fullscreen mode

This way, you don't have the two effects of a) changing items and b) returning the changed array. By switching to forEach you choose to only have effect a). By changing to my proposition you choose to have effect b). Both decisions are quite fine, just wanting both seems indeed somehow redundant.

Collapse
 
smeijer profile image
Stephan Meijer

You have a bug though 😇

const newItems = items.map(i => ({ ...i, id: userId }))
Enter fullscreen mode Exit fullscreen mode

But yeah, I see where you're coming from, and I do agree that that pattern is often the better one. It was just not the message I was trying to give with this article. You might be interested in reading dev.to/smeijer/don-t-stop-mutating... as well.

Thanks for sharing though. Appreciated 🙂