You can put any type of value in an array in JavaScript. You can have numbers, strings, booleans, arrays, and objects. So what should the default sort function sort by? Sorting by numbers makes sense, but what if it wanted to sort strings instead?
When you don’t know what value is in an array ahead of time you can’t assume how to sort it. When you’re controlling the program you can provide a sort function for the type of values you know will be in it, but when you’re writing the standard default sort function, there’s only one type that you can convert all the other types to safely and simply in the most predictable way, which is strings.
ImpossibleRubiksCube@programming.dev 1 year ago
JavaScript is what’s called an “untyped” language, so here, it assumes that the numbers are words, and tries to sort them alphabetically. Specifically, it tries to sort them alphabetically as a dictionary would in a left-to-right language like English. In this case, just as “apple” would come before “asterisk”, 100000 would come before 21.
(Some would argue that it’s more of a “weakly typed” language, I know, but I’m trying not to be pedantic here.)
Sorting them as actual numbers would require some extra explicit instructions and guides. Most typed languages, like C, aren’t like this.
affiliate@lemmy.world 1 year ago
is there a good reason for javascript to work like that? python also isn’t typed like C and it sorts integer lists in the “normal” way, so it seems avoidable. (i don’t really know what im talking about here. i’ve never used javascript and i’m not familiar with how typing works under the hood.)
Quasari@programming.dev 1 year ago
Mainly because JavaScript was designed to work along side HTTP in a browser. Most of its input will be text, so defaulting common behavior to strings makes some sense.
severien@lemmy.world 1 year ago
That’s misleading at best and most likely just false, and it’s worrying it’s so upvoted.
There’s no historical record explaining why this was designed this way, but we can infer some things. HTTP is very unlikely factor, XHR / AJAX has been added years after the
.sort()
function.The trouble with JS arrays is that they can contain any values - e.g.
[false, undefined, 1567, 10, “Hello world”, { x: 1 }]
. How do you sort those? There must be one function to compare every combination of value, but how do you compare string and object?The simple answer to that is
.toString()
- every object has it, it will compute something, and often it will work well enough.affiliate@lemmy.world 1 year ago
thank you for the explanation, that does clarify things
floofloof@lemmy.ca 1 year ago
It’s also an incorrect alphabetical sort in many languages that use accented characters. For a correct sort you need to pass it something like the localeCompare function.