Why JavaScript Sort Doesn't Work Like You Think 🤔 #shorts
Video: Why JavaScript Sort Doesn't Work Like You Think 🤔 #shorts by Taught by Celeste AI - AI Coding Coach
Watch full page →Why JavaScript Sort Doesn't Work Like You Think 🤔
When you use JavaScript's default sort() method on an array of numbers, it may not sort them numerically as expected. This happens because sort() converts elements to strings and compares their UTF-16 code unit values, leading to surprising results.
Code
const arr = [10, 2, 1, 21];
// Default sort converts numbers to strings and sorts lexicographically
console.log(arr.sort());
// Output: [1, 10, 2, 21]
// To sort numbers correctly, provide a compare function
console.log(arr.sort((a, b) => a - b));
// Output: [1, 2, 10, 21]
Key Points
- JavaScript's default
sort()converts array elements to strings before comparing them. - This string-based comparison sorts numbers lexicographically, not numerically.
- Providing a compare function like
(a, b) => a - benables proper numeric sorting. - Always specify a compare function when sorting numbers to avoid unexpected order.