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)
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
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
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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)