Sort Mutates the Array
You'll learn that calling sort() changes the original array directly and returns that same modified array, not a copy.
The Core Idea
When you call .sort() on an array, JavaScript doesn't create a new sorted version and leave your original array untouched. Instead, it rearranges the elements in place, modifying the array you called it on. The method then returns a reference to that same, now-sorted array.
This is important because if you're not expecting this behavior, you might accidentally destroy data you wanted to keep in its original order.
How It Works
const numbers = [3, 1, 4, 1, 5];
const result = numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 1, 3, 4, 5] — original array is sorted!
console.log(result); // [1, 1, 3, 4, 5] — same array
console.log(numbers === result); // true — they're the same object
Notice that numbers and result point to the exact same array. The original array was modified, and sort() simply returned a reference to it.
Analogy
Think of sort() like reorganizing books on your shelf. You're not creating a second shelf with the books in order—you're moving the actual books around on your existing shelf. When you're done, you point to that same shelf and say "there, it's organized."
If You Need the Original
If you need to preserve the original array, create a copy first using methods you've already learned:
const original = [3, 1, 4, 1, 5];
const sorted = original.slice().sort((a, b) => a - b);
console.log(original); // [3, 1, 4, 1, 5] — unchanged
console.log(sorted); // [1, 1, 3, 4, 5] — sorted copy
Key Takeaway: sort() mutates the original array in place and returns a reference to that same array, not a new one. Make a copy first if you need to preserve the original order.