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.
Comment on I'll just sort it myself
ImpossibleRubiksCube@programming.dev 1 year agoJavaScript 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.
floofloof@lemmy.ca 1 year ago
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.Quasari@programming.dev 1 year ago
You are probably correct. I don’t know if it’s true, it’s probably more likely it was a way for it not to fail.
I said HTTP mainly because HTML is plaintext because of it. 1.0s main purpose was to manipulate the page. Of course Array objects weren’t added til 1.1, when netscape navigator 3.0 released, but it was still mostly 1.0 code.
I originally thought there was a precursor to microsofts XMLHTTP in an earlier version due to the 1997 ECMAScript documentation specifically talking about using it both client and serverside to distribute computations, but it was far more static. So, I’m probably just wrong.
affiliate@lemmy.world 1 year ago
thank you for the explanation, that does clarify things