Advertisement
Advanced JavaScript, Arrays & Array Methods

How does sort() compare values by default, and how do you fix numeric sorting?

Short answer

By default sort() converts elements to strings and compares UTF-16 code units, which sorts numbers incorrectly (e.g. 10 before 2). Pass a compare function returning negative/zero/positive to sort numerically.

Save JavaScript mock interview
Advertisement
AModel answer
By default sort() converts elements to strings and compares UTF-16 code units, which sorts numbers incorrectly (e.g. 10 before 2). Pass a compare function returning negative/zero/positive to sort numerically.
[10,2,33,4].sort(); // [10,2,33,4] -- wrong
[10,2,33,4].sort((a,b) => a-b); // [2,4,10,33] -- correct
Real-world example
Sorting a list of prices or ages correctly requires an explicit numeric comparator.
Likely follow-ups
  • Is Array.prototype.sort() guaranteed to be stable in modern JS engines?
Related topics