JavaScript Array Sort
The sort() method sorts array elements and is one of the most useful but potentially confusing array methods. Understanding how sort() works, especially with compare functions, is essential for correct sorting behavior.
Sorting Arrays
The sort() method sorts array elements in place, modifying the original array. It also returns the sorted array, but the original is changed. If you need to preserve the original, create a copy first with slice() or the spread operator: [...arr].sort(). Sorting in place is memory efficient but destructive—be mindful of when you need to keep the original order.
By default, sort() converts all elements to strings and sorts them alphabetically (lexicographically) based on UTF-16 code unit values. This works perfectly for strings but produces unexpected results for numbers. For example, [40, 100, 1, 5, 25].sort() returns [1, 100, 25, 40, 5] because it compares "100" < "25" as strings. Always use a compare function for numeric sorting.
To sort numbers correctly, provide a compare function: arr.sort((a, b) => a - b) for ascending order, or arr.sort((a, b) => b - a) for descending order. The compare function receives two elements (a and b) and should return negative if a < b, positive if a > b, or zero if equal. The subtraction shortcut (a - b) works perfectly for numbers but won't work for objects or custom comparisons.
The reverse() method reverses the order of elements in an array in place, modifying the original array. The first element becomes the last, the last becomes first, and so on. reverse() is often used after sort() to get descending order, though using a compare function is more flexible. Like sort(), reverse() returns the modified array.
Both sort() and reverse() modify the original array, which matters when working with const arrays or when you need to preserve the original data. If immutability is important, create a copy before sorting: const sorted = [...original].sort(). Modern JavaScript style often prefers immutable operations to avoid unexpected side effects.
// Alphabetic sort
const fruits = ["Banana", "Orange", "Apple"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Orange"]
// Reverse
fruits.reverse();
console.log(fruits); // ["Orange", "Banana", "Apple"]
// Numeric sort (wrong way)
const numbers = [40, 100, 1, 5, 25];
numbers.sort();
console.log(numbers); // [1, 100, 25, 40, 5] (string sort!)
// Numeric sort (correct way)
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 25, 40, 100]
// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 25, 5, 1]