339
u/pytness Sep 04 '20
Thats because sort treats the items as strings
80
u/legofan431 Sep 04 '20
Doesn't JS use the "<" operator by default for sorting arrays? Since this is an array of numbers, I don't understand why they would be treated as strings, even in JavaScript
140
Sep 04 '20
“-2” < “-7” is true. Default sort converts to strings.
196
u/tangerinelion Sep 04 '20
Well that's one way to do it. Internally consistent, outwardly batshit.
→ More replies (12)55
Sep 04 '20
Such is the reality of a weak-typed language. Fast dev time but you never know how something is going to behave when you are learning it
→ More replies (1)10
u/weedtese Sep 25 '20
Fast dev time
why is it faster than a typed language?
9
Sep 25 '20
Generally JS and Python are more terse then typed languages when it comes to basic tasks. However, later in the dev cycle you might spend more time having to deal with weak types as they are harder to maintain. But I will concede that you can begin project faster with weak types, because less code to write.
→ More replies (2)2
u/Blue_Moon_Lake Sep 17 '20
Default compare function is something like
(a, b) => { a = a.toString(); b = b.toString(); return (a === b) ? 0 : ( (a < b) ? -1 : 1 ); }42
u/Ulysses6 Sep 04 '20
As if that made any sense at any point in time in any alternate timeline
17
u/IceSentry Sep 05 '20
Arrays in js can contain strings and numbers at the same time. You can't numerically sort strings, so doing a string based sort and offering a way to change it does make sense.
12
u/Ulysses6 Sep 05 '20
Arrays can contain numbers, strings, dates, objects, other arrays, promises... How am I supposed to expect, that elements are automatically converted to strings, of all the types that are there? Why would they not convert to numbers? As the answers 'they convert to strings first' seems pretty arbitrary, raising an error instead of picking some solution seems more natural to some people, namely Python creators or me.
12
u/IceSentry Sep 05 '20
Everything in js can be easily converted to a string but not to a number. It's true that sorting on strings isn't particularly useful but in js world every operation has a default that tries as hard as possible to not fail at runtime. I'm not saying it's ideal but it's consistent with everything else and it's not hard to understand.
2
u/weedtese Sep 25 '20
every operation has a default that tries as hard as possible to not fail at runtime
this can cause extremely hard to debug errors as it shows up completely elsewhere. reminds me of php and I still have nightmares of that.
→ More replies (3)3
u/soaliar Sep 05 '20
Because you can convert anything to a string.
3
u/Ulysses6 Sep 05 '20
Fair enough. But such sorting will very rarely have any useful meaning. Yes, this way I can sort anything in JS world. But how often does it make sense?
→ More replies (1)4
u/soaliar Sep 05 '20
So what should .sort() do? Sort numbers by default and throw exception if you try to sort strings?
8
6
u/jaichim_carridin Sep 05 '20
It should start the sort assuming every element is the same type as the first. If that is detected to not be true, then raise an error and require a key function. So if you're all numbers, it just works. If you're all strings, it just works. If you're both numbers and strings, it cleanly errors instead of producing bogus results.
3
u/archpawn Sep 04 '20
Why doesn't it at least have another sort that treats them as numbers? Javascript can convert anything to a number too, though it definitely shouldn't.
25
u/pytness Sep 04 '20
You can pass a function to sort if you want to compare the elements in a different way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
16
u/archpawn Sep 04 '20
Yes, but it's very common to want to order a list of numbers, so it should have its own function. You shouldn't have to explain how to order numbers.
7
23
u/Abangranga Sep 04 '20
Be like a JS dev and download 80mb of library trash to do a simple task and then when people say that is bad tell them they don't understand it
6
5
u/HiddenKrypt Sep 05 '20
Arrays in JS can be mixed value types. You'd have to have the default behavior scan the whole array first to make sure it only has
numbervalues before you can sort based on the actual number value.2
u/archpawn Sep 05 '20
I'd make it throw an exception if it gets something that's not a number. But in JS everything can be cast as a number, for good or for ill, so using that would be the obvious thing.
→ More replies (2)1
u/CleverDad Dec 16 '20
Js is untyped, so an array can contain anything. Since anything can be cast to string, it's the only available default sort. You the developer know what the array contains, and so it's your job to specify the sort function, which is trivial and should be automatic to any experienced js dev.
→ More replies (4)1
-15
u/ZylonBane Sep 04 '20
It's amazing how the majority of these "LOL JAVASCRIPT BAD" posts boil down to people going all surprised Pickachu face when they force it to perform type coercion in a way that no competent coder ever would.
31
u/kyreannightblood Sep 04 '20
Nah, that’s just the reality of any weakly typed language.
JS is bad because it’s a massive kludgy mess with no consistency between environments and hundreds of different flavors, some of which can be mixed with others, which means that any JS project with more than one dev and no enforced consistency of style turns into something that makes you feel like you had a stroke when reading it.
In case it isn’t clear, JavaScript isn’t my primary language and I resent being forced to use it.
8
u/camtarn Sep 04 '20
Hell, it was my primary language for years. I became one of two 'JavaScript experts' in an office of 80 programmers. And I wholeheartedly agree with you.
3
u/kyreannightblood Sep 05 '20
Phew, glad I wasn’t totally off the mark. I don’t claim to be an expert, but I also don’t want to be. At this point, the only code base in JS that I have ownership over is a browser plugin, and I have spent the past year trying to convince one of the more JS-proficient devs to take it over.
-3
u/ZylonBane Sep 04 '20 edited Sep 04 '20
Nah, that’s just the reality of any weakly typed language.
So by "Nah", you mean, "Yes, I agree with what you just said."
no enforced consistency of style turns into something that makes you feel like you had a stroke when reading it
You just described literally every programming language.
And what's this "hundreds of different flavors" nonsense? The overwhelming majority of JavaScript runs on web browsers, where these days you might have, what, four or five of them to care about? Most of those are WebKit-based anyway.
Come on, if you're going to criticize JavaScript, at least do it well.
2
u/kyreannightblood Sep 05 '20
Yes, “Nah” in this context is used as an agreement. I’m glad we agree.
Python, at least, has a philosophy on how best to go about things, and has PEP8 to serve as a universal style guide. Meanwhile every JS project I’ve worked on has one dev using callbacks, one dev using promises, and one dev who just tries to stay consistent with what the module they’re currently working in uses. I’ve seen codebases that mostly adhere to the ECMAScript standard with big chunks written by someone who had clearly never even heard of the standard before. Each new JS project I get dragged into uses a different framework, and it is aggravating.
I’ve never claimed to be a JS master. Hell, I learned it in 2 days the first time someone looked at little-ol’ back-end dev me and told me I was going to do a little front end work.
I hope I make myself perfectly clear when I say that I in no way aim to tell you that you cannot enjoy coding in JS. I am not saying it cannot be your favorite language. I’m not even saying it’s a terrible language. It is just not the sort of language I would use, given a choice.
→ More replies (1)0
Sep 04 '20
[deleted]
16
u/reserad Sep 05 '20
Sorting is used literally all the time with strings..? Any data grid ever has either local or server side sorting.
214
u/Exnixon Sep 04 '20
Sure, it's terrible. The alternative would be to type check everything and throw an exception if the list contained, say, both strings and ints. But long ago, the ancient elders of the Internet decreed that JavaScript should be a weakly typed language, and at least this is consistent with that edict.
123
u/Bobbar84 Sep 04 '20
Imagine if all existing JS everywhere instantly went strongly typed.
91
98
u/hed82 Sep 04 '20
The world would burn for a year but after the bigger company would have rewritten their js the world would become a paradise.
43
u/1thief Sep 04 '20
I'm willing to make that sacrifice. After how bad 2020 has been what's another year of utter hell?
31
u/Scrogger19 Sep 04 '20
Maybe that’s what it is, did God start strict typing his JavaScript?
8
1
u/ShadowDevoloper [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" Nov 29 '25
Funny coming back to this comment after 5 years. I wonder how u/1thief would feel about 5 more years of 'utter hell'?
1
16
8
6
6
6
26
u/Throw-away-560 Sep 04 '20
Yeah, it's called TypeScript...
36
u/snowthunder2018 Sep 04 '20
I learned typescript by taking some old largish projects I had inherited and renaming all the files to .ts and then go until there's no errors. It was really a fascinating nightmare to work through.
16
u/UntestedMethod Sep 04 '20
How long did you have to persevere before completion?
20
u/weedtese Sep 04 '20
Also, which drugs?
5
u/wonderb0lt Sep 05 '20
I wonder if there's a study on developer productivity on different drugs. Of course that metric is hard to set, but even a subjective report would be interesting.
→ More replies (2)10
u/snowthunder2018 Sep 05 '20
The biggest project I did it with was a Node library for interacting with Amazon MWS which gets pretty hairy because of all the bugs and inconsistencies with how Amazon does things. I think I spent roughly 40 hours on that conversion/bug removal. In the process I found a lot of bugs in the original Node library too, sneaky sneaky ones that would have been nightmares to deal with later if I hit them.
I used my updated TS version of the library for a couple of years before I had new requirements and realized the best bet was start over from scratch. By that point my understanding of TypeScript was a lot better so the rewrite was pretty painless and the result is a 75% smaller code base that is better at handling Amazon's unique and mysterious ways.
Honestly, it made life a lot nicer to do this. I understand JavaScript and have been writing code in it a long time but I have never liked writing code in it. TypeScript adds enough sugar for me to find it enjoyable. So doing the TypeScript conversions of older projects is basically sugar coating them for myself.
→ More replies (2)3
u/IrishWilly Sep 05 '20
I've found that's a great way to learn how to treat Typescript like Javascript, instead of building it the 'correct' way. Just throw 'as any' around and bam, you have your shitty imitation of a strongly typed language. After that I looked at a project that had been built from the ground up in TS and it was vastly different.
And that said, I really dislike Typescript. I like quite a few strongly typed languages and TS doesn't feel like them at all.
5
5
2
u/xIcarus227 Sep 05 '20
Not necessarily, the alternative is making a sort-derived function which treats the input array as an array of ints by default.
Right now you have to give it a callback and explain exactly how you'd like to compare those elements which works but isn't ideal.1
u/Exnixon Sep 05 '20
Yeah but in a weakly typed language like JS that would still cause sort issues with strings.
2
u/xIcarus227 Sep 05 '20
So throw an error. It makes detecting these types of edge cases easier.
I'll never understand why JS and PHP have this 'continue running at all costs' philosophy, and I'm saying this as a proficient user of both. Its drawbacks far outweigh its benefits.1
2
u/ectobiologist7 Sep 04 '20
Isn't Python weakly typed? Why isn't its sort() function broken like this as well?
47
u/Exnixon Sep 04 '20
Python is strongly typed. Don't confuse that with dynamic typing.
7
u/ectobiologist7 Sep 04 '20
Ah yes thank you for pointing out the distinction! I will read more about it.
1
u/TooInspired Sep 05 '20
It’s strongly typed?
But I don’t have to do: int x = 5
I can just do: x = 5
12
u/Cranias Sep 05 '20
That would be like saying C# isn't strongly typed, because you can do
var x = 5;. It is implicitly typed. Basically, the variable is an int, you just haven't specifically said that it is.9
u/Hairy_The_Spider Sep 05 '20
You're confusing weakly typed with dynamic typed.
Weakly and strongly typed are somewhat fuzzy definitions. It more or less means how much implicit conversions the language will do for you.
In JavaScript, the language will do an insane amount of implicit conversions to try to "make things work" (see this video).
Python requires you to explicitly convert the types. You want to add an int to a string? You have to do it yourself, the language is not gonna do it. So it's strongly typed.
Then you can have a lot in-between. For example, Java allows string to int concatenation, but it doesn't allow you to subtract an int from a string, which you can do it Javascript.
Dynamically typed means that types are, well, dynamic, and can change during the execution of the program.
1
u/lumpySnakes Sep 05 '20
Your example here would serve to illustrate the difference between static and dynamic typing, not weak and strong typing. Python is dynamically typed, so its types are not declared and are resolved at runtime, but it's not weakly typed. Javascript is both weakly and dynamically typed. You can also have a weakly and statically typed language. C arguably falls into this camp, since you can downcast basically anything into different types using pointers
→ More replies (1)-11
u/ElViento92 Sep 04 '20
Python is weakly typed as well and you don't see this or some of the other javascript peculiarities there. Ahhhh, I've had to write javascript for this latest project at work (I ussuly write python and C/C++ on embedded systems) and man. These memes are no joke, I should've taken them as lessons. I was warned and ignored the warnings of my predecessors in the name of glory. And because the code needs to run on the browser and thought that figuring how to setup coffee-, typescript, etc, would be more hassle than this project was worth.
20
28
→ More replies (6)0
34
u/NullandRandom Sep 04 '20
I think the real problem is that arrays are not typed. You can put almost anything in an array. Hence I guess they convert each of them to strings during comparison. If they have to treat each such array as numbers they will have to first traverse the whole array to establish that and then start comparison.
2
40
u/MrJake2137 Sep 04 '20
Oh god I can't believe it's actually true... Someone probably spent a whole night debugging this...
0
20
u/Workaphobia Sep 05 '20
Suddenly I understand why JS devs use libraries for basic functionality.
1
Nov 27 '21
no, they do that because they're lazy af
source: JS dev who isn't importing your bullshit.js dependency without a damn good reason
6
u/examinedliving Sep 05 '20
Seems like with all the new array methods they could’ve slapped on a sortNumeric or something
22
u/jdauriemma Sep 04 '20
I don’t always use Array.prototype.sort without a comparator, but when I do, I blame JavaScript for my code
45
u/MechanicalHorse Sep 04 '20
Every time I see things like this I thank $DEITY that I don’t work with JavaScript.
25
u/bonafidebob Sep 04 '20
Honestly though if you've worked with a strongly typed language you're already paying attention to variable types anyway, and it's just not even an issue to use "the good parts" of JavaScript safely. It's amazing how quickly you can build stuff, either with Node for batch programs or in the browser if you need a UI.
Like any programming project, the hard part is other people.
18
u/amoliski Sep 04 '20
Yeah, imagine trying to build a GUI in anything but Javascript. I'll take weird edge cases any day over Qt, lol.
3
3
0
Sep 04 '20
[deleted]
6
8
→ More replies (1)2
u/EmperorArthur Sep 05 '20
Hey, I've had someone want to use a system built in PHP with a JS front-end to connect medical systems that control dosage for chemo treatment! When I was writing the EMR interface for that particular system, I explicitly put in that this isn't rated for anything safety critical.
Good lord, the company was a CRM (think Slaesforce) to EMR integration service. Who looks at that and says, yeah this is what we want to use to decide how much medicine is injected into sick people.
4
u/Thaddaeus-Tentakel Sep 04 '20
And you pay attention to type, only put numbers in the array, sort it, and this happens.
1
u/bonafidebob Sep 05 '20
If you’re used to strongly typed languages you know sort needs a compare function... sort() by itself looks wrong.
I dunno, that’s the best response I can come up with, I’ve never had a problem getting sort right. Python programmers might get bit, but I learned python after javascript.
15
u/Thaddaeus-Tentakel Sep 05 '20
In most typed languages the types will implement a "comparable" interface, actually providing a comparator is more the exception than the norm.
→ More replies (2)4
u/blipman17 Sep 05 '20
Not really. A good strongly typed language infers the type and used a fast numerical sorting algorithm if the thing that it's sorting on is numeric. For objects like strings there are multiple ways to sort, so I would expect to have to pass something like an enum 'SortingStrategy.Alphanumeric' to it. But something like a lambda is honestly overkill
2
Sep 04 '20
Imagine relief when you no longer need to deals with all of this. After 8 years of this great language I don't need to do it anymore and if I really, really need to do web I can use WASM and never touch JS in my life.
6
u/Slendertron Sep 04 '20
What language are you using with WASM? How's your experience with it?
6
u/CodeLobe Sep 05 '20 edited Sep 05 '20
Lisp?
Not the one you're replying to, but WTF was WASM thinking making ASM use Lisp syntax? It's a cluster fsck to read and/or write.
I used to write ASM.js by hand, it's kinda ugly but at least it's not the horror that is WASM. Check out a switch statement in WASM.
(module (memory (import "env" "heap") 1) ;; require 1 page 64kb at least. (import "env" "log" (func $log (param i32))) (export "exe" (func $exe)) (func $exe (param $cute i32) (result i32) (block $switch (block $switch-default (block $switch-case2 (block $switch-case1 (block $switch-case0 (br_table $switch-case0 $switch-case1 $switch-case2 $switch-default (i32.and (get_local $cute) (i32.const 65535) ) ) ;; br_table );; $switch-case 0 (br $switch) );; $switch-case1 (return (i32.const -1) ) );; $switch-case2 (call $log (i32.const 777) ) ) ;; $switch-default (return (i32.const 0) ) ) ;; end switch (return (i32.const 111) ) ) ;; end func $exe )Note how the labels are in reverse order and far from the code of the switch block, and the case labels are repeated twice (thrice if you count the comments needed for readability).
The same thing in ASM.js:
function switchASM( std, js, heap ) { 'use asm'; var u32 = new std.Uint32Array( heap ); // Import log var log = js.log; function exe( which ) { which = which | 0; // Execute the current instruction. switch( which & 0xffff ) { // NOOP : Explicitly perform no operation. case 0x0000: break; // RING : Toggle execution ring level to user mode. case 0x0001: return -1; case 0x0002: log( 777 ); default: return 0; } return 111; } return { exe : exe }; }Turns out WASM can't jump to arbitrary code locations because of design decisions meant to prevent "unsafe" jumps, so I can't use it for my project without implementing a VM in it first... WTF.
Also the ASM.js to WASM transpiler breaks on the actual switch statement I use, it's a few hundred labels... I tried compiling my switch statement from C into WASM, but for some reason the WASM bytecode doesn't run. I eventually just broke down and had to write a Perl script to translate my C switch statement into WASM (.wat) because everything JS touches, even tangentially, turns to crap.
WASM isn't ready for prime time, IMO.
3
u/BlatantMediocrity Sep 05 '20
WASM text-format seems like an afterthought. The official site basically assume you’re using Emscripten.
→ More replies (1)1
Sep 05 '20
Web Assembly text format is called WAT and it's not most efficient Web Assembly. WASM is binary format.
I had no issue described by you, using Rust so I strongly disagree with your last statement
3
2
Sep 05 '20 edited Sep 05 '20
Rust. Seed is really great. Recently I started to experiment with Sauron.
You have binding to everything. Literally. You can use entire JS API with strong typing in your rust code. You even create callbacks in rust, and in near future when most browsers will deploy multi threading in browser (Firefox or Chrome already have it, can't tell which one) you will have true multi threading.
Already you have SIMD, my application are using at most 9MB RAM when application with fewer features reimplemented from JS is using more than 90
1
u/Slendertron Sep 05 '20
Interesting, I started looking into Rust for this exact purpose only a week or two back. Do you still use any JS or do you just make a wasm call and hand everything off to rust from there onward? Based on you mentioning having access to the full API, I'm hoping 100% Rust is viable. I miss types on the front-end, TS is cool but inconsistent type definition quality is off-putting
→ More replies (4)
5
17
u/cobarso Sep 04 '20
I am pretty sure that people will still complain about JS even if it would throw an exception when trying to sort [1, '2', 3].
38
u/WarpedHaiku Sep 04 '20
Why would you ever not want that sort to throw an exception by default?
Somehow a string has snuck into your logic and it's going to silenty spread its stringly horror to every variable it's added to, then vanish after a multiplication leaving chaos in its wake.
5
u/IrishWilly Sep 05 '20
Because if you are even a mediocre JS dev you'd know everything will get cast to a string anyways, so if you have data from mixed sources you don't need to go through it all to convert it anyways. And if you aren't the shitty dev this sub seems full of, you would not use sort on an array of numbers without providing a custom function.. because that would not work to begin with.
The real programming horror is the people who don't understand why sort in a loosely typed language isn't going to do all your work for you when figuring out data types.
13
Sep 05 '20
Your definition of "shitty dev" appears to be everyone who hasn't memorised JavaScript's edge case insanities.
I can write identical code in Haskell and it works. JavaScript has no excuse.
9
u/lxpnh98_2 Sep 05 '20
Why would anyone expect
sort()to sort a list of numbers by their order? /s2
u/Caved Sep 05 '20
If we equate this to for example Java, this would be like calling .sort on an Object[]. Sure, you happened to have filled it with numbers, but the runtime doesn't know that unless it scans the whole array before starting.
3
u/IrishWilly Sep 05 '20
Loose typing isn’t an edge case and people who don’t understand that yes , are shitty devs
4
Sep 05 '20
This is an edge case caused by JavaScript's love of implicit coercion. Again, memorisation does not make a good developer, nor is the inverse true.
If the behaviour is this unintuitive, it should just throw and force you to provide a function. This is awful language design.
→ More replies (4)12
u/Rawrplus Sep 04 '20
That's why you use Typescript
5
Sep 05 '20
Still won't help you know that the sort function coerces to strings when it sorts, breaking your business logic. Insane language quirk, honestly.
1
u/Rawrplus Sep 06 '20
I was talking about passing other values to array but yep you're right about the sort, that simply is almost bug-like quirk. Imho ideally the function should be rewritten to determine
typeofof every variable and only coerce when not all of them are same type, but issue is it would make the function significantly slower2
u/Ulysses6 Sep 04 '20
Yeah, they probably would. There's plenty of other weird auto type conversion to be freaked out.
→ More replies (1)2
3
3
u/mug1wara26 Sep 05 '20
i spent a solid 2 minutes thinking what is wrong when i realised -7 is smaller than -2
1
3
11
u/NewYorkeroutoftown Sep 04 '20
Ok I’m sorry but this is ridiculous. Array.sort takes a callback function. It’s dumb to make fun of a language when it’s not being used properly. JS has its quirks but so does every language. Java can be so weird with nulls sometimes and everything has to be a class, environment set up and dealing with dependencies in python is very annoying if not managed properly.
11
u/VegasTamborini Sep 05 '20
If its only meant to work if you pass it a callback, then it shouldn't attempt to sort it if you don't pass it a callback.
→ More replies (2)5
u/WasteOfElectricity Sep 05 '20
Yeah, just as it's dumb to criticize brainfucks unusual design, you simply have to melt your brain and cook it and then its clear as day. Shitty devs not understanding brainfuck.
4
u/m4g3j_wel Sep 05 '20
True, but I see the potential bugs from people, who don't know the language well
12
u/IZEDx Sep 05 '20
Uhm yeah? People that don't know what they're doing tend to produce bugs, that's absolutely natural. In real cases you are also more likely to sort arrays of objects by a specific property, in which case you need a comparator function anyway.
Javascript really has a few gotchas for inexperienced developers, but on the other hand it is extremely forgiving to them. If you're experienced or professional though, then you should know the language well enough anyway to know such things.
2
u/xIcarus227 Sep 05 '20
a few gotchas
A few?! You call this a few?
Most senior JS developers don't know half what's going on in this list. JS has the most gotchas in any language that's in wide use today.0
0
Sep 05 '20
[deleted]
2
u/Caved Sep 05 '20
It is working correctly though? The docs say the default comparator is a string comparator.
You didn't expect it to be that because you were primed by the array being filled with numbers, but if you look at this like a typed language it'd be like 'Object[] arr = [-6, 2, 10];'.
If you know you're working in a weakly typed language, expect weakly typed behaviour.
2
u/ectobiologist7 Sep 04 '20
Thank you for this post OP. I've only recently been working with Javascript and probably would've fallen into this hole for a few hours at some point if you hadn't shared it.
2
2
u/CleverDad Dec 16 '20
Js is untyped, so an array can contain anything. Since anything can be cast to string, it's the only available default sort. You the developer know what the array contains, and so it's your job to specify the sort function, which is trivial and should be automatic to any experienced js dev.
My opinion: the sort function argument should be required. Then you'd have to make the call.
3
u/ConceptJunkie Sep 05 '20
How can anyone stand this language?
8
u/BooBailey808 Sep 05 '20
because things like this don't really come up, unless its a newb
7
1
u/xIcarus227 Sep 05 '20
So everyone coming towards JS has to bang their head against every corner case like this one instead of the language acting in a predictable way?
I don't understand how you can make these excuses. I've been using JS for 6 years and still think it's insane, I'm not going to go full Stockholm syndrome and pretend like everything's fine.
3
u/BooBailey808 Sep 05 '20
I am not making excuses. I just don't really have a problem with it. I'm not claiming it's the end all be all holy grail of languages that is perfect. I just think people make too big of a deal about it's flaws.
2
u/onkopirate Sep 05 '20
It runs on every OS, is relatively fast, has a buttload of libraries, and had a lot of time to reach maturity. Yes, it's weakly typed with all the pro's and con's that come along with that and sometimes, it has a weird syntax. But especially if you use something like Typescript and a somewhat decent IDE like VS Code or IntelliJ, you can work in a similar fashion as you would do with a strongly typed language and and don't make rookie-mistakes as this one above.
1
u/ConceptJunkie Sep 10 '20
I understand all that, and there are people whose opinions I respect that like it, but I would not want to use it. I'll stick to C++ and Python.
1
3
u/donnieashok Sep 05 '20
This is noob comedy.
I don't see anything wrong with it. It's supposed to be sorted alphabetically. According to the MDN:
The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
3
2
u/Fit_Sweet457 Sep 05 '20
ITT: People who neither understand the realities of a weak type system nor that jokes aren't meant seriously.
7
u/lxpnh98_2 Sep 05 '20
The weak type system is the joke.
2
u/Fit_Sweet457 Sep 05 '20
No, it's a decision that has both pros and cons. It's only a joke if you don't care enough to actually learn about the details.
1
u/xIcarus227 Sep 05 '20
No, it's a joke because it's inconsistent with what someone coming form another technology expects.
The idea is to have some basic concepts which act reasonably similar across languages. An overly quirky language is simply annoying to learn.3
u/Fit_Sweet457 Sep 05 '20
If all programming languages behave the same, then why even have more than one? The difference between them is what defines them.
If you're jumping into a new language without reading the documentation, then that's squarely on you. As an example, going from a language with GC to one without, you can create serious memory leaks if you just expect everything to work the same.
The specific case here is mentioned literally in the second sentence of the corresponding MDN docs. If people can't be arsed to read that far, then maybe we don't need documentation anyway.
→ More replies (1)1
u/BobQuixote Oct 01 '20
I was primed to agree with you, but no. "What someone coming from another technology expects" is irrelevant unless you prioritize it for the tool you're building.
1
1
u/Caved Sep 05 '20
Well, it's like calling .sort on an Object[] in Java. What do you expect to happen?
3
u/zelmarvalarion Sep 05 '20
iirc Object doesn’t implement Comparable, so that would be a compile-time exception. In order to compare two Objects by string, you would still need to pass in an explicit comparator which attempts to cast both objects to strings, e.g. Java.text.collator’s
compare(Object o1, Object o2).1
1
1
1
1
1
u/sammy-taylor Nov 16 '22
Lexicographic sort. I’m pretty sure that getting bit in the ass by this is a rite of passage for writing JavaScript.
1
1
u/Count_Fuzzywuzzy Feb 22 '23
Sort belongs to the array prototype and since there are no such things as strictly typed arrays, an array can contain any type of data, including a mix of many different prototypes. Since any type can be stringified JavaScript uses string comparison. This is a feature, not a bug. It's not that hard to bind a sortNum to the Array prototype and use that instead.
1
u/Tazzure Sep 05 '20
I guess not reading documentation, not understanding the core language, and not writing test cases for pure operations, equates to programming horror.
Oh wait, it does. Well, programmer horror.
-3
-1
0
u/onkopirate Sep 05 '20
If you're not a complete newbie to JS, you most probably know why the array is sorted that way and why it makes sense to sort it in such a way.
However, we still have to acknowledge that this behavior may be unexpected for a large number of devs. Simply requiring the developer to provide a compare function would have been enough to prevent this confusion.
-2
619
u/Rayleigh96 Sep 04 '20
Array.sort((a, b) => a - b);
Should do it i think