const users = [{ id: 1, name: 'Alice', age: 25 }];
function birthday(arr) {
return arr.map(user => {
user.age++;
return user;
});
}
const updated = birthday(users);
console.log(users[0].age);
console.log(updated[0].age);const users = [{ id: 1, name: 'Alice', age: 25 }];
function birthday(arr) {
return arr.map(user => ({ ...user, age: user.age + 1 }));
}
const updated = birthday(users);
console.log(users[0].age);
console.log(updated[0].age);Bug: map returns a new array but user is still a reference to the original object. user.age++ mutates the original.
Explanation: Spread { ...user, age: user.age + 1 } creates a new object for each element. The originals are untouched.
Key Insight: map creates a new array but elements remain shared references. Spread objects inside map to create independent copies.