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
Take the quiz on the full lesson page
Test what you've read ยท interactive walkthrough
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.
Ready? Take the quiz on the full lesson page โ
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.