🟡 MediumFix the Code🐛 Debug Challenge

Object mutation in array map

Buggy Code — Can you spot the issue?

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!

Fixed Code

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 Explained

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 }.

More Fix the Code Debug Challenges

🟢 EasyDeep clone breaks with JSON.stringify🟡 Mediumthis lost in event listener🔴 HardPrototype pollution vulnerability🟡 MediumProxy trap modifies original object directly

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab