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