🟑 MediumWhat's Wrong?πŸ› Debug Challenge

Array sort mutates original

Buggy Code β€” Can you spot the issue?

function getSorted(arr) {
  return arr.sort((a, b) => a - b);
}

const nums = [3, 1, 4, 1, 5];
const sorted = getSorted(nums);
console.log(nums);   // [1, 1, 3, 4, 5] β€” mutated!
console.log(sorted); // [1, 1, 3, 4, 5]

Fixed Code

function getSorted(arr) {
  return [...arr].sort((a, b) => a - b); // spread to copy first
}

// Or with toSorted() (ES2023, immutable):
function getSorted(arr) {
  return arr.toSorted((a, b) => a - b);
}

const nums = [3, 1, 4, 1, 5];
const sorted = getSorted(nums);
console.log(nums);   // [3, 1, 4, 1, 5] β€” unchanged βœ“
console.log(sorted); // [1, 1, 3, 4, 5] βœ“

Bug Explained

Bug: Array.prototype.sort() sorts IN PLACE and returns the same array reference. It doesn't create a copy.

Explanation: Always copy before sorting: [...arr].sort() or arr.slice().sort(). ES2023 adds toSorted() as an immutable alternative built-in.

Key Insight: sort() mutates in place. Always [...arr].sort() to avoid mutation. toSorted() is the new immutable version (ES2023).

More What's Wrong? Debug Challenges

🟒 EasyAccidental global variableβ†’πŸŸ‘ MediumWrong comparison with NaNβ†’πŸ”΄ HardInfinite re-render in React useEffectβ†’πŸŸ‘ MediumSpread only shallow-copies nested arraysβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab