function updateUserAge(users, userId, newAge) {
return users.map(user => {
if (user.id === userId) {
user.age = newAge; // MUTATES the original!
return user;
}
return user;
});
}
const users = [{ id: 1, name: 'Alice', age: 25 }];
const updated = updateUserAge(users, 1, 26);
console.log(users[0].age); // 26 — original mutated!function updateUserAge(users, userId, newAge) {
return users.map(user => {
if (user.id === userId) {
return { ...user, age: newAge }; // new object, not mutation
}
return user;
});
}
const users = [{ id: 1, name: 'Alice', age: 25 }];
const updated = updateUserAge(users, 1, 26);
console.log(users[0].age); // 25 — original unchanged ✓
console.log(updated[0].age); // 26 — new array updated ✓Bug: user.age = newAge directly mutates the original object. Even though map returns a new array, the objects inside are still references to the originals.
Explanation: Spread { ...user, age: newAge } creates a new object. map returns a new array. Neither the original array nor its objects are touched.
Key Insight: map creates a new array but doesn't deep-clone the elements. Always spread to create new objects when updating: { ...obj, changedProp: newVal }.