DEV Community

Discussion on: TIL: The pecularity of the sort function

Collapse
 
joshcollinsworth profile image
Josh Collinsworth

This is a great heads-up! I had run into this problem, but honestly never understood why before. Now I'll remember. :)

I don't know for sure why it works this way, but my guess is that, because the function takes an array that could potentially contain any mix of values and types, they all need to be converted to something common in order to be compared. And since String is the only type you can (somewhat) reliably convert other types into, that was the choice.

Presumably, it was decided that the function shouldn't do any other conversion (like adding zeroes before numbers), in order to keep the function simple, and preserve the original data with as little munging as possible (and probably to avoid other, similar issues that would've arisen with trying to predict input, like how many zeroes to add, whether they would be added before or after the type conversion, and whether incoming string values containing numbers would be affected).

Collapse
 
varjmes profile image
james

This is an excellent suggestion, thanks!