MediumArray & Object Mutations🐛 Debug Challenge

map returns new array but objects inside are still references

Buggy Code — Can you spot the issue?

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);

Fixed Code

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 Explained

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.

More Array & Object Mutations Debug Challenges

EasyAssignment copies reference — both variables point to same arrayMediumObject.assign first argument is mutatedMediumSpread is shallow — nested array is still shared

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab