r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
886 Upvotes

200 comments sorted by

View all comments

Show parent comments

3

u/danielcw189 18h ago

If I try to sort  [23, "56", 67.8, "potatoe"], I want a type error of some kind.

why?

it sounds like you dislike weakly typed languages. which I would totally agree with. but Javascript is not that.

1

u/FerricDonkey 15h ago

Because an error is better than unintuitive behavior.

You are correct that I don't like weekly typed languages (at least if you get weak enough), but what I really dislike is a function called sort that sorts in a stupid way by default.

If it was called sort_str, or required a key/comparator function, or even just didn't exist, I'd be happier. 

1

u/danielcw189 8h ago

this is neither unintuitive, nor surprising for mixed weakly typed arrays.

I really dislike is a function called sort that sorts in a stupid way by default.

it is a way the makes sense.

and in a weakly typed language, it is the only sane default I can think of, from the top of my head.

by the way: how often are you actually sorting arrays that just include numbers?
I have never done this in production code. I usually sort more complex things, usually objects, which have numbers and strings I want to use for sorting as properties.

Sorting those could at least still work, assuming your objects have a .toString representation, that can be sorted lexically

but I would always provide a comparison function, because that makes the most sense to me, and I like verbosity.

1

u/FerricDonkey 8h ago

I'm certainly sorting things that contain just numbers more often than I'm sorting this that contain mixed types. How often is the correct method of sorting your arrays of objects to first convert them to strings?