Why Does Array.sort() Change My Original Array?
I ran into this while working with a small JavaScript project and it caught me off guard.
const numbers = [5, 2, 9, 1, 7];
const sorted = numbers.sort((a, b) => a - b);
console.log(sorted);
console.log(numbers);
Both arrays are sorted.
I originally expected sorted to be a new array and numbers to stay unchanged.
I know there are ways to avoid this, like using [...numbers].sort(), but I’m curious:
Do you usually remember which JavaScript methods mutate the original array, or do you just check when you’re unsure?
What other JavaScript methods have surprised you by changing the original data?