EasyModern JS🐛 Debug Challenge

sort() mutates the original array

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.join(','));
console.log(sorted.join(','));

Fixed Code

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

const nums = [3, 1, 4, 1, 5];
const sorted = getSorted(nums);
console.log(nums.join(','));
console.log(sorted.join(','));

Bug Explained

Bug: Array.sort() sorts in place and returns the same array. nums and sorted are the same array after the call.

Explanation: Spread creates a copy before sorting. The original nums is untouched.

Key Insight: sort() mutates in place. Always copy first: [...arr].sort(). ES2023 adds arr.toSorted() as a built-in immutable alternative.

More Modern JS Debug Challenges

EasyManual swap loses original valueMediumRegex with global flag alternates true/falseHardIterator is single-use — second loop produces nothingMediumCustom error class not extending Error

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab