sort(): Sorting Arrays In Place
You'll learn how to use sort() to rearrange array elements into sorted order, modifying the original array directly.
What sort() Does
The sort() method rearranges the elements of an array in place, meaning it changes the original array rather than creating a new one. Like reverse(), it's a mutating method that returns the modified array.
Think of it like organizing books on a shelf—you're physically moving the books around on the same shelf, not creating a duplicate shelf.
Default Sorting Behavior: A Surprise
Here's the catch: sort() converts elements to strings and sorts them lexicographically (alphabetically) by default. This works great for text, but produces unexpected results with numbers:
const letters = ['c', 'a', 'b'];
letters.sort();
console.log(letters); // ['a', 'b', 'c'] ✓ Works as expected
const numbers = [10, 2, 30, 1];
numbers.sort();
console.log(numbers); // [1, 10, 2, 30] ✗ Oops! '10' comes before '2' alphabetically
Because sort() treats everything as strings by default, '10' comes before '2' (just like 'apple' comes before 'banana' alphabetically).
Mutates the Original Array
Like other mutating methods you've learned, sort() changes the original array:
const fruits = ['banana', 'apple', 'cherry'];
const result = fruits.sort();
console.log(fruits); // ['apple', 'banana', 'cherry'] - original changed
console.log(result); // ['apple', 'banana', 'cherry'] - same array
console.log(fruits === result); // true - same reference
When Default sort() Is Useful
Default sort() works perfectly for alphabetizing strings:
const names = ['Zoe', 'Alice', 'Bob'];
names.sort();
console.log(names); // ['Alice', 'Bob', 'Zoe']
Key Takeaway: sort() rearranges array elements in place using lexicographic (alphabetical) order by default, which works for strings but treats numbers as strings, often producing unexpected results with numeric data.