MediumState & Immutability🐛 Debug Challenge

Sort mutates array state — original order lost

Buggy Code — Can you spot the issue?

let names = ['Charlie', 'Alice', 'Bob'];

function getSortedNames() {
  return names.sort(); // mutates names!
}

const sorted = getSortedNames();
console.log(names.join(','));  // should still be unsorted
console.log(sorted.join(','));

Fixed Code

let names = ['Charlie', 'Alice', 'Bob'];

function getSortedNames() {
  return [...names].sort(); // copy first, then sort
}

const sorted = getSortedNames();
console.log(names.join(','));   // original preserved
console.log(sorted.join(','));

Bug Explained

Bug: Array.sort() mutates in place and returns the same array. names is now sorted — the original order is destroyed.

Explanation: Spreading creates an independent copy. Sorting the copy doesn't affect the original names array.

Key Insight: sort(), reverse(), splice(), push(), pop() all mutate the array. For state: always copy first ([...arr].sort()), or use ES2023's toSorted(), toReversed(), toSpliced().

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab