DEV Community

Discussion on: Don't stop Mutating

Collapse
 
bravemaster619 profile image
bravemaster619

You shouldn't have included projects attribute in the first place.

Anyways, deleting something somewhere in your code will cause unpredictable behavior in the long run.

You better leave original object as it is, because mutating objects WILL affect other parts of your code.

I agree on the second example (Unpredictable behavior) but the first one is kinda misleading. I would say.. Readability vs Maintainability

I will definitely choose this way:

const users = fetchUsers(100);
const newUsers = [];

for (let i = 0; i < users.length; i++) {
  const { age, ...newUser } = users[i];
  newUsers.push(newUser);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
smeijer profile image
Stephan Meijer

Yes, in the perfect world, projects wouldn't have been there in the first place. Unfortunately, we don't live in the perfect world. Sometimes we use external API's, and get more data than we need. Sometimes, we fetch data from MongoDB, and deleting a bit of data is easier done on the backend than it is through aggregation piplelines.

You better leave original object as it is, because mutating objects WILL affect other parts of your code.

No, it doesn't have to. If the mutation is abstracted away, there is no issue (my getUsersWithoutProjects example). And that's the point of the article. It really isn't that black and white.

I will definitely choose this way:

And that's okay. Everyone has their own preference. The fact that you choose this style, doesn't make someone choosing the other wrong.

Collapse
 
bravemaster619 profile image
bravemaster619

Sometimes, we fetch data from MongoDB, and deleting a bit of data is easier done on the backend than it is through aggregation piplelines.

Yeah, maybe it's easier to do in frontend. BUT you need to do in BACKEND. For the sake of security and performance. Right?

If the mutation is abstracted away, there is no issue (my getUsersWithoutProjects example)

I already said that I agree on getUsersWithoutProjects.

The problem lies in this one:

const users = fetchUsers(100);

for (let i = 0; i < users.length; i++) {
  delete users[i].age;
}
Enter fullscreen mode Exit fullscreen mode