r/programminghorror • • Jun 12 '25 • This 1

Javascript Javascript is filled with horror

Post image
2.4k Upvotes

337 comments sorted by

View all comments

Show parent comment

4

u/TorbenKoehn Jun 12 '25

It's not bad design. All alternatives are worse (including just throwing an error)

It's sorting by "best guess" and the "best guess" is forcing it into a string, since all values can do it in JS.

Why does everything need to throw errors? You see it sorts your 11 after your 1, you look it up, realize the mistake you made, make it never again.

If it would throw an error you'd look it up, too, so the work involved is exactly the same.

4

u/arto64 Jun 12 '25

irb(main):001> [1, 2, "3", 4, "book"].sort

(irb):1:in `sort': comparison of Integer with String failed (ArgumentError)

What's wrong with this? This makes perfect sense.

You will miss errors in your business logic, because nothing will indicate that something is wrong.

1

u/TorbenKoehn Jun 12 '25

It's not the same

By your idea, [1, 2, 3, 4]... would already throw the error in JS (numerical sorting is the topic here). But in Ruby that doesn't happen: It uses a <=> function on each element tuple. Similar to calling 1.compare(2) or "a".compare("b") respectively. And 2.compare("3") throws the error because it can't compare an integer with a string

This is essentially the same way it works in JS, just that it's not <=>/.compare, but .toString().localeCompare since JS doesn't have something similar to <=> or a Comparable interface. Maybe in the future, but at no point would someone go and change the .sort() function for it, since it would basically break the web.

In JS, you simply pass compare to the .sort() function, and the default, .toString().localeCompare, can simply work on compare any type as it casts them to strings.

It's also often what you want, especially during web development.

2

u/arto64 Jun 12 '25

I know how this all works, I'm saying it's bad design in JavaScript, in my opinion.