• affiliate@lemmy.world
      link
      fedilink
      arrow-up
      7
      ·
      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
        link
        fedilink
        English
        arrow-up
        20
        arrow-down
        2
        ·
        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.

      • kevincox@lemmy.ml
        link
        fedilink
        arrow-up
        13
        arrow-down
        1
        ·
        edit-2
        1 year ago

        The hard part is sorting values of different types.

        Python 2 had a order of built it types. Something like None < bool < numbers < strings. This means that you could sort anything like JavaScript and behaves fairly reasonably.

        Python 3 takes the “safer” approach and comparisons of different types throw an exception. (You can override the comparison behavior for your own types and do something different).

        JavaScript has conventionally been a very loosely typed language. So it almost certainly wouldn’t have chosen the exception throwing option. It does something similar to Python 2. But instead of just directly comparing the values of different types it converts them to strings first, then compares everything as a string. This is probably the most reasonable option. Otherwise you would have problems because 10 &lt; "2" and "2" &lt; 3 but 3 &lt; 10. How can that work? You have no total ordering! So basically because the comparison operators convert to strings if either argument is a string the default sort comparator really doesn’t have a choice but to do convert to string. The other option would be to define a total order just for the sort function but that seems more confusing.

    • floofloof@lemmy.ca
      link
      fedilink
      English
      arrow-up
      3
      ·
      edit-2
      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 or Intl.Collator.