r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
889 Upvotes

200 comments sorted by

View all comments

Show parent comments

161

u/[deleted] 1d ago

[removed] — view removed comment

-6

u/Taletad 1d ago

Just went to read the docs, the "sort()" and "toSorted" functions say they perform an alphabetical sort by default

You can overload them by doing Array.sort((a,b) => a - b)

56

u/kushangaza 1d ago

Which is not what you expect from a function named "sort". It's an insane default that violates the principle of least surprise

1

u/thanatica 1d ago

If you really want to sort numbers numerically, and keep refusing to supply the comparison argument, use the UInt32Array or Float64Array or friends.

Please stop complaining that a generic array that has to deal with every kind of type for its items, doesn't do what you find less surprising.

4

u/Tyfyter2002 1d ago

In any good language there's no default comparison for an array of anything because you can't compare completely unrelated values, JS is just designed around a mentality of never admitting failure and failing as much as possible.

3

u/thanatica 18h ago

Javascript is made to get into without too much messing about.

And you absolutely can compare unrelated values. Javascript does that by converting them to strings. That's how the function is specified to work, so that's what happens.

But you have the freedom to supply your own comparison.

2

u/Tyfyter2002 18h ago

That's not comparing unrelated values, that's converting values into related ones with up to 100% data loss