• kevincox@lemmy.ml
    link
    fedilink
    arrow-up
    12
    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.