DEV Community

Discussion on: Stop mutating in map, reduce and forEach

Collapse
 
vasiliikovalev profile image
Vasilii Kovalev • Edited

Thank you for the article! Totally agree with map and reducer purposes.

I personally find myself avoiding data mutations at all, and if I want to extend existing data, I do it on the data item's copy:

function addUserId(userId) {
  return (item) => ({ 
    ...item, 
    userId,
  });
}

const items = [
  { id: 1 },
  { id: 2 },
];

const newItems = items.map(addUserId('abc'));
Enter fullscreen mode Exit fullscreen mode

Thus it frees us from unnecessary side effects and heartaches.

Other cases, like pushing to or changing external data conditionally, are covered by reduce (as in your last example).

It seems the last time I used forEach, it was run of unit tests with different test data, but the same expect (like in jest-in-case before I found out about it).

What real use cases for mutating data instead of copying it can you imagine?

Collapse
 
hoffmann profile image
Peter Hoffmann

Hy, sorry to have doubled your comment, I did only see that you basically proposed the same change after reading it a second time.

Collapse
 
smeijer profile image
Stephan Meijer

Oh, I'm definitely with you there. I just felt that if I would make that function immutable, that people might mis the point I was trying to make for map vs forEach.

That being said, I do have a couple of mutable functions on the server side. It does perform better, and there isn't always a need to keep it immutable. Think for example transformations that are applied after fetching from db and before sending to client.

Also on the client now I think about it. I sometimes add "private properties" to objects that I need to recall later. If I don't use them for display (/to trigger rerenders) I might just as well mutate the object.

It is really on a case by case basis tho.

Collapse
 
valiice profile image
Valentin

This allocating memory on every iteration would result in horrible performance.