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(','));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: 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.