← TechnologyThe essentials of

sort(): why numbers are sometimes arranged as text

Publisher: ResumeMaker • 1 source

Published: 22 Oct 2026 13:13 · Updated: 22 Oct 2026 13:13

AI source check: 21 Oct 2026 10:06. This is not editorial approval.

In a few sentences

In brief

sort() changes the array itself. Without a comparison function, values are compared by their textual representation.

Useful to know

For numeric ascending ordering, use an overt comparison function : numbers.sort((a, b) => a - b). Without such, sort() converts items to text and compares them by UTF-16 code units, which can give an unexpected numerical order. [1]

For example, [2, 10, 3].sort() becomes [10, 2, 3]. With (a, b) => a - b, the result is [2, 3, 10]. The negative result of the function puts a before b, positive - after it.

The second common error is the assumption that the original remains intact . sort() arranges in place and returns the same array. [1] If you want to keep the input of numbers, make a copy : const ordered = [...numbers].sort((a, b) => a - b);.

In objects, specify which property you are comparing. The order by price, title and date are different tasks. A comparison function should match the selected rule, not just return a random true or false.

Sources

For further detail and to check the information:

  1. [1] MDN — Array.prototype.sort ↗