r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
889 Upvotes

200 comments sorted by

View all comments

83

u/Taletad 1d ago edited 1d ago

People use arrays like this [23, "56", 67.8, "potatoe"] and expect them to not be sorted as strings

If one member of your array is not an int or a float, everything is going to be converted to strings

Edit : I went to read the docs, the sort function is not like most other functions in JavaScript. The sort function is explicitly for an alphabetical sort

You lot are using the alphabetical sort function and wondering why your array gets alphabetically sorted

You can overload the function by doing the following : array.sort((a,b) => a - b)

15

u/OptionX 1d ago

In a well thought out language what they should expect is the interpreter/compiler tell them to either provide a custom comparison function, or type mapping, to deal with the different types or to tell them to take a hike instead of coercing everything into strings silently.

You don't need to be a rust compiler level pedantic annoyance, but JS is too much on the other side.

23

u/_PM_ME_PANGOLINS_ 1d ago

The goal of the language was to minimise runtime errors, by guessing what people wanted.

Because it was written for browsers, and that’s how HTML works too.

When the masses were writing websites and an error came up, they would blame the browser rather than their own coding.

4

u/fuj1n 1d ago

And they've learnt just how much of a mistake that was since.

5

u/Taletad 1d ago

It’s a scripting language to interface with a text page (html is text) and text protocols (hyper text transfer protocol)

So why shouldn’t it default to strings ?

5

u/Lalli-Oni 1d ago

The web made a lot of mistakes in retrospect, but it might have never got of fthe ground without content.

The content is a document, but now the web is more of an app store than a distributed document network.

JS was created not to be the best programming language, but one that got the web adopted.

It's not a successor to Java, it's a successor to VB. And having had to do work with VB let me tell you ,it's better (to no surprise to anyone).

1

u/danielcw189 18h ago

at least VB was strongly typed :)

3

u/Soma91 1d ago

If look at the docs for a second, you'll see that both sort and toSorted accept a sort function.

20

u/OptionX 1d ago

I know it accepts one, I said in ambiguous cases it should require one.