Default Sort
sort converts items to strings and sorts lexicographically by default.
This can surprise you with numbers like 10 coming before 2.
JavaScript Tutorial
sort orders array elements in place. Without a compare function it sorts as strings.
For numeric and custom ordering, you should pass a compare function.
Sorting is common for lists, leaderboards, and UI tables.
Knowing how sort behaves avoids subtle bugs.
array.sort()
array.sort((a, b) => a - b)const nums = [10, 2, 5];
nums.sort();
console.log(nums); // [10, 2, 5] as stringsDefault sort is lexicographic, not numeric.
const nums = [10, 2, 5];
nums.sort((a, b) => a - b);
console.log(nums); // [2, 5, 10]Use a compare function for numeric order.
sort converts items to strings and sorts lexicographically by default.
This can surprise you with numbers like 10 coming before 2.
Provide a compare function for numeric or custom sorting.
Return a negative number for a before b, positive for a after b, and 0 for equal.
sort mutates the original array.
Clone the array first if you need to keep the original.
const users = [{ age: 30 }, { age: 20 }];
users.sort((a, b) => a.age - b.age);
console.log(users);Compare object fields for custom sorting.
const nums = [3, 1, 2];
const sorted = [...nums].sort((a, b) => a - b);
console.log(nums, sorted);Clone to avoid mutating the original.
Without
const nums = [10, 2, 5];
nums.sort();With
const nums = [10, 2, 5];
nums.sort((a, b) => a - b);Provide a compare function for numbers.
Clone before sorting if needed.
Return negative, zero, or positive numbers.
Yes, it sorts in place.
Provide a compare function like (a, b) => a - b.
Use (a, b) => b - a.
Practice: Sort an array of scores in descending order.
const scores = [20, 5, 30];
// TODO: sort descending
One Possible Solution
const scores = [20, 5, 30];
scores.sort((a, b) => b - a);
console.log(scores);Yes, sort changes the original array.
Default sort compares strings, not numbers.
Use (a, b) => b - a.
Try sorting numbers and strings to see differences.