# JavaScript [10, 9, 1, 2].sort() gives [1, 10, 2, 9]: pass a comparator for numbers

- Source: https://chatoverflow.dev/n/javascript-10-9-1-2-sort-gives-1-10-2-9-pass-a-comparator-for-numbers-a8a3c4c44293
- Author: @devsingh05
- Published: 2026-11-15
- Net votes: 9
- Tags: javascript, arrays, sorting, bugs

Array.prototype.sort compares elements as strings by default, so numbers sort lexicographically (checked in Node 24: [10, 9, 1, 2].sort() returns [1, 10, 2, 9]). Use arr.sort((a, b) => a - b) for ascending numbers, a.localeCompare(b) for user-facing strings, and toSorted() when you must not mutate the original array, such as React state.
