JavaScript sort() arranges elements alphabetically as strings by default, which surprises developers when sorting numbers. Providing a short comparator function fixes numeric sorting, and ES2023 toSorted() keeps your original array untouched.
[10, 2, 1].sort() Gives [1, 10, 2]Without a comparator, sort() converts every element to a string and compares UTF-16 character codes. Because "10" starts with "1", "10" comes before "2".
To sort numbers properly, pass a compare function (a, b) => a - b for ascending order or (a, b) => b - a for descending order.
Use toSorted() (or [...arr].sort(...)) when you do not want to mutate the original array in place.
const scores = [40, 100, 1, 5, 25];
const ascending = scores.toSorted((a, b) => a - b);
const descending = scores.toSorted((a, b) => b - a);
console.log("Original:", scores);
console.log("Ascending:", ascending);
console.log("Descending:", descending);
const products = [
{ name: "Keyboard", price: 75 },
{ name: "Mouse", price: 30 },
{ name: "Monitor", price: 240 },
];
const byPrice = products.toSorted((a, b) => a.price - b.price);
const byName = products.toSorted((a, b) => a.name.localeCompare(b.name));
console.log("By price:", byPrice.map((p) => p.name));
console.log("By name:", byName.map((p) => p.name));
numbers.sort() without a comparator: Always supply (a, b) => a - b when sorting numeric arrays.sort(): arr.sort() modifies arr in place and returns the same reference. Copy with [...arr].sort() or use arr.toSorted().a - b: Subtracting strings yields NaN. Use a.localeCompare(b) for alphabetical sorting across accented characters.Use ES2023 arr.toReversed(), or clone first with [...arr].reverse(). Calling arr.reverse() directly mutates the original array.
If (a, b) returns a negative number, a comes before b. If positive, b comes before a. If 0, their relative order stays unchanged.
Array.prototype.sort() stable?Yes, since ES2019 all major engines implement a stable sort, keeping equal items in their original relative order.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.