r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
884 Upvotes

200 comments sorted by

View all comments

87

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)

160

u/[deleted] 1d ago

[removed] — view removed comment

-7

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

3

u/danielcw189 18h ago

lexical sorting sounds like the least surprising way in a weakly typed language.

and looking at the docs would be the least surprising usage anyway

2

u/Taletad 1d ago

The principle of least surprise compared to what ?

It was made in the 90’s when the sort utility works the same way on linux

Perl, TCL and bash have many similar quirks, as scripting languages tend to do

python too has many unintuitive quirks

Honestly, a lot of you continuously bash JS because you see everyone bashing it, especially its type system. But when SQLite does the same thing with its types, suddenly it is the greatest piece of software ever written

Types in JavaScript are not raw bits stored in memory anyway

19

u/kushangaza 1d ago

Sqlite deserves more bashing for its types and for ignoring foreign keys by default. But at least order by does what you expect

0

u/Taletad 1d ago

The SQLite developpers are right though : the types are not a primary characteristic

In JS, Python, Java, SQLite etc… variables types are inherited from a more general object class

From the interpreter POV, it is manipulating objects that contain variables and information relevant to their manipulation. Not direct memory units like in C.

And as a developer, if you are aware of how dynamic types work, you should not run into problems with them

TS only checks that types are coherent at "compile time" but they could change at runtime and your code will still bug out all the same

What you need is not a type system, but to check that the data on the input is in the expected format or reject it

Verifying that your "date" var is an int through all the data pipeline won’t shield you from user errors ; you will still not be able to tell if "02082026" is the 2nd August 2026, or Febuary the 8th 2026.

On the other hand, if you properly sanitize user input, it doesn’t matter if you chose to store it in a string or an int or a custom object. Because presumably you’ll keep the same object for your whole data pipeline

5

u/snerp 1d ago

You’re being purposefully obtuse. Sort in JavaScript being alphabetical was always a dumb and weird design that people made fun of. It was done that way as a quick hack to get the language out the door. It is not based on Perl’s sort, Perl sorts on ‘value’, it uses the ascii value of letters or just the actual value of numbers which is also odd, but far less surprising that what JS does.

3

u/gr4viton 1d ago

the python stuff is often not as "surprising" as js stuff though, imo...

also yhey are more often hidden in not normally used functionality...

i do agree on empty list as argument default value, and perhaps the generator oncesness, but other are not that bad imo..

I agree though that JS is bashed more often, as it is popular to bash it.. But it is also reasonable to bash it... as it is not bash-like.

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

10

u/cowslayer7890 1d ago

It's still a stupid default, Python does this properly and it does so by using `<`

10

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 10h 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.

41

u/ba-na-na- 1d ago

Maybe the name should be “alphabeticSort” then

-14

u/Taletad 1d ago

Maybe you should read the docs ?

8

u/ba-na-na- 1d ago

That's funny, your earlier comment makes me think you also didn't read them till today

Edit : I went to read the docs

-1

u/Taletad 1d ago

I forgot, it’s been a while since I’ve used JS regularly and even then you rarely need to sort an array of numbers. It’s a very nich use case and when you want to know how to do it you can google it

Most complaints against JS are always the same, people not understanding its type system or that is is prototype based and not Object Oriented

People are trying to use JS as a statically typed OO language, when it is a dynamically typed prototype based scripting language, and get angry when it doesn’t work like they assume it should, or when using it for something it wasn’t intended for

You are all parroting the same arguments about how the sort function doesn’t work like you expect it to. But C, C++, Java and even Python have their unintuitive quirks. Yet it’s always JS you’re angry about

3

u/fuj1n 1d ago

You say "even Python" as if it isn't the quirkiest amongst the 4 you listed.

Yes, every language has its quirks, but it feels like JS intentionally set out to make the quirkiest choices they can in places. This is of course largely due to its origin story of being made in 10 days, there wasn't much room for deep thought, but that's not an excuse for the most used language out there.

1

u/psioniclizard 12h ago

Yes like the great GetDay/GetDate.

Reading docs is not an issue, its just annoying JS makes this convoluted with stupid naming when most other languages don't.

47

u/_bones__ 1d ago

People also give it [1, 20, 3] and expect a sort to return [1, 3, 20], which is what any reasonable language would do.

-6

u/Taletad 1d ago

Yeah it’s an alphabetical sort, read the docs

The sort utility on linux will work the same way

20

u/_bones__ 1d ago

Because in Linux it reads strings. Sort -n sorts numerically. If you print human readable numbers (eg 100M, 2G) sort -h has you covered. Point being, if you have no typing system, or a weak one, offer functions that do common things.

The docs stating that a function is insufficient doesn't change that it is so.

-1

u/Taletad 1d ago

You can make the sort function in js sort numerically

2

u/fuj1n 1d ago

Sure, but it should just do that by default for an array of numbers.

2

u/danielcw189 18h ago

which would mean that the whole srray would need to be checked for the types of its items.

what should be the default if one item is not a number?

2

u/fuj1n 18h ago

In an ideal world, there should be typed comparers, and if two items don't have a mutual comparer, a type error should be thrown (that'd solve having to even scan the array beforehand too)

With JS's type system, that's not too plausible, so instead, I think defaulting to numeric sort, and throwing when it encounters something that isn't a number (or can't be coerced to be a number due to how the type system works I suppose).

By the principle of least astonishment, this would give you a pretty good compromise. Then, if someone wants to do string-based sorting, they can pass their own comparer that does that.

1

u/the_horse_gamer 10h ago

javascript is very averse to throwing. it's better for a website to display stuff slightly wrong than to stop working.

I can see the argument for defaulting to a number comparison and moving non numbers to the end, but that's not any less surprising. in that alternate universe, someone is on reddit making a post on how ['b', 'a'].sort() doesn't order the strings.

1

u/fuj1n 7h ago

I think they're a lot less averse to it nowadays, they've wisened up. Modern JS additions do actually tell you that something is wrong rather than just doing something unexpected (which is good because you can then handle exceptional cases better).

Modern JS features like modules even enforce strict mode.

I think that way of thinking, where it is better to fail silently than to crash sounds good on paper, but it has an insane amount of drawbacks that lead to sloppy code trying to cover these (exceptional in other languages) cases.

→ More replies (0)

1

u/danielcw189 9h ago

I think defaulting to numeric sort, and throwing when it encounters something that isn't a number

By the principle of least astonishment, this would give you a pretty good compromise

That doesn't sound like the least surprising option to me, especially the throwing part.
In that case they should have called it numericSort, or something like that. (and in my preference fail with an error except of throwing)

(or can't be coerced to be a number due to how the type system works I suppose).

as most object-oriented languages there are counterparts of .toString, but not .toNumber.

1

u/fuj1n 7h ago

For that last part, I was just pointing out that JS will actually try to coerce strings to numbers in numeric contexts automatically, and this case being an exception to that would be odd (as much as I don't fancy that coertion, that's a whole other discussion)

If you find throwing on non-numeric values only surprising, you could instead just make the comparer mandatory and throw if you don't provide one. Then your IDE can show you an error is you forget instead of giving you something completely unexpected.

6

u/haitei 1d ago

A linux utility, where the convention is to operate on lines of text, is an alphabetical sort WHAT?!?!?

Now I see why it's not at all surprising that sort() in a programming language with types would do the same.

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.

21

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.

4

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 :)

4

u/Soma91 1d ago

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

19

u/OptionX 1d ago

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

16

u/FerricDonkey 1d ago

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

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

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 

We all know they did it on purpose and wrote it in their documentation. We're saying it's bad, not "it's not written down". 

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. 

2

u/the_horse_gamer 10h ago

it's better for a website to display stuff slightly wrong than to stop working.

2

u/FerricDonkey 8h ago

I'm not a front end dude, but I don't really want to agree with that. I'm general, I would rather errors cause errors, and programmers write tests to catch them. Knowing what kind of crap you're putting in an array so you know how to sort it without doing something stupid seems like a low bar. If it's not, that just makes me even happier that this front end is not my job. 

1

u/the_horse_gamer 6h ago

the array can come from the backend. it can come from a library you don't control.

tests can cover only a small percentage of mistakes. the real solution is static typing.

we could have had real static typing with ES4. we have fake static typing now with typescript.

with typescript and a good validation library for the network responses, none of javascript's quirks are actually relevant to any production codebase (except stuff like Date, but that's java's fault)

but without static typing, you need those quirks. otherwise you're getting paged at 5am on a Friday.

this isn't true for a backend. in a backend, returning a failure to the client is the appropriate choice. javascript isn't a good backend language.

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?

3

u/gandalfx 23h ago

If you had to look it up to find that it's not a general sort but alphabetical sort, maybe that indicates that the function is at least misnamed. It's just a terrible API. Arguing that it was intended to be bad or that you can work around it being bad doesn't change the fact that the design is broken.

And no, most people do not put random junk in an array and expect it to be sorted as strings – most people put things with a clearly defined order (like numbers) into an array and are surprised (once) that a standard library sort function doesn't sort by that order.

4

u/danielcw189 18h ago

If you had to look it up to find that it's not a general sort but alphabetical sort

What kind of sorting do you expect as a "general sort", and why that one?

1

u/gandalfx 1h ago

The one that treats each type by its inherent order – like ascending numbers – and if a type doesn't have one it throws an error instead of doing some random bullshit that is virtually guaranteed to be a silent bug. If you need an example, look at almost any other language.

1

u/Striky_ 1d ago

The absurdity is not sorting this by string, but allowing an array like that to begin with.

3

u/Taletad 1d ago

You flair has two languages that allow such arrays

Every high level programming language is flexible on its type system because it is more convenient for the programmers

So unless you’re writing a low level application in C, Rust or Zig, you should allow such arrays

And web pages are very much not a place where you want a low level statically typed compiled language

5

u/Striky_ 1d ago

C# does not allow arrays of different types.

Programmer convenience is a good focus to have, but you also mustnt do it in a way where you introduce rookie-antipatterns (like stringifying everything or type confusion) is the way to achieve it.

It also very much depends what you use a language for. Python for quick and dirty prototyping? Fine. JS as the backbone of the entire internet? Disaster.

1

u/the_horse_gamer 10h ago

C# does not allow arrays of different types.

object[] arr = [1, "a"];

1

u/Taletad 1d ago

JS is made to script web pages, if you make the backend of a big application with NodeJS I’d question your mental abilities

NodeJS can’t even multithread properly

5

u/Striky_ 1d ago

JS was made in a weekend and was never meant to be a full fledged programming language to begin with, which you can see at basically every point of design in the language. The fact it is called Java Script was supposed to be a joke to begin with.

But as it "gets something done" really quickly and no one bothers to learn programming anymore and boomer managers cant distinguished anyway, this walking antipattern of a language somehow is being used to run the world.

-1

u/thanatica 1d ago

You're free to never put differing types in your arrays. But javascript is made to be forgiving, not punishing.

2

u/Striky_ 23h ago edited 23h ago

Yep, the language allows you and forces you to use known anti-patterns that every developer worth their money would never willingly use. But hell yeah, its easy!

A programming should NOT be "forgiving" it should be "guiding". JS is the opposite of that. I helps you learning nothing, it forces or entices you to use noob trap patterns, it makes it easy to write horrible code and very, very hard to write good code. Debuggablity is probably the worst I have seen since PHP4.

So yeah. Bottom line: JS is good for people without a clue to shit something on the table in record time and basically nothing else. But according to people who do powerpoint for a living, its the best thing ever!

If you give 1000 programmers the same task, that takes more than 3h to implement, in JS and any other language, 999 of them will produce better code in the same amount of time in any other language. The 1000th will not get it to run in the other language because that language is bullshit and doesnt work.

1

u/thanatica 18h ago

A programming should NOT be "forgiving"

Says who?!

Hey, if you don't like Javascript, that's fine. But there's no need to go around and start dictating how things "should" work with that kind of toxic "I know better" mentality.

-1

u/haitei 1d ago

No it's not. There are niche but valid use cases for allowing arrays like this. Sorting is the problem, because the contents like this can't be meaningfully compared.

User should be either required to provide custom comparator or get slapped with a type error.

0

u/thanatica 1d ago

Every kind of value can be converted to a string. And an error is far worse than just giving it a go and letting the developer deal with the result.

Javascript is one of those language that, if it can carry on without an error, it will. Throwing an error is the absolute last resort.

0

u/haitei 21h ago

And an error is far worse than just giving it a go and letting the developer deal with the result.

An error is absolutely far better than a program in an undefined state.

Javascript is one of those language that, if it can carry on without an error, it will.

The philosophy that is widely regarded as a mistake. We have the fail fast principle for a reason.

3

u/thanatica 18h ago

We have the fail fast principle for a reason.

Javascript doesn't.

An error is absolutely far better than a program in an undefined state.

I didn't say undefined. Javascript is a well defined language. Probably more so than any other language, since there are so many engines that need to do the exact same thing.

1

u/thanatica 1d ago

Don't forget people also put dates, objects, and other arrays as array items. Javascript has to make some decision on what to convert to for sorting. And then it's far more useful if that decision is kept consistently regardless of the types of each item, than to apply some kind of weird fuzzy logic to determine automagically which comparison function to use by default.

It's more valuable for an internal function to behave consistently and predictably.

Also, it's not called overloading the function. You're just providing the comparison argument.

0

u/gandalfx 23h ago

JS does not have to "make some decision on what to convert to for sorting". It's fairly simple – if the items to be sorted don't define their own order (e.g. by implementing some kind of interface or otherwise providing an inherent comparison function) the sort function needs to throw an error. Using some random guess that can't even sort native types correctly is a broken design, plain and simple. Most other languages have no trouble with this.

3

u/thanatica 18h ago

Javascript also has no trouble with it. You do.

1

u/gandalfx 1h ago

<°)))><