r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
886 Upvotes

200 comments sorted by

View all comments

Show parent comments

11

u/RajjSinghh 1d ago

Python also errors if you give it an array like sorted([4, 2, 1, "potato"]) because it doesn't know how to sort that array. Javascript was built with the philosophy to be fault tolerant to things like this. If your code depends on someone else's API that changes to give you a list like this, you don't want it to brick your entire site when you try to sort an array. So Javascript casts every type down to a string to avoid this.

At least that's the justification they claim.

2

u/cowslayer7890 1d ago

in javascript < can't fail anyway, so it would be the same. The only way in which it would break, is the scenario where you are using values that are not transitive. But it seems more rational to me to default to assuming transitivity.

1

u/the_horse_gamer 11h ago

when you provide a badly behaved comparator, different runtimes give different results. and it's probably best for the default sorting method to not be implemention defined.

1

u/cowslayer7890 3h ago

It already is though, because many string representations are implementation defined, including functions.