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]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: 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).