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?
sora
August 23, 2026, 10:40pm
3
It’s a common side effect of many in-place operations. I usually make a copy first, like [...myArray].sort(), if I need the original array later.
Yeah, it’s definitely tripped me up before. I usually just use slice() to make a shallow copy if I need to preserve the original.
I always forget this one too. I wish it was more obvious in the docs that it changes the array.
It’s interesting how toUpperCase comes to mind for string changes, but strings are actually immutable in JavaScript.
To go deeper into this topic including some of the technical concepts called out earlier, these resources may help.
Learn how to perform common tasks such as declaring, adding, removing, and merging arrays in JavaScript.
Learn how to perform common tasks such as declaring, adding, removing, and merging arrays in JavaScript.
This caught me off guard when I first started working with JavaScript too. sort() mutates the original array because it sorts the array in place and returns a reference to that same array.
I usually check the documentation when I am unsure rather than trying to memorize every mutating method. splice(), reverse() and push() are a few other common ones worth remembering. Using immutable patterns like […numbers].sort() can also help avoid unexpected side effects.