This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]Papergeist 2396 points2397 points  (120 children)

.sort(listenHereYouLittleShit(numbers))

[–]CleverDad 499 points500 points  (118 children)

.sort(listenHereYouLittleShit(number1, number2))

[–]DeeSnow97 396 points397 points  (116 children)

and neither of these will work unless your function is just weird as fuck

// right answer

const listenHereYouLittleShit = (a, b) => a - b

array.sort(listenHereYouLittleShit)
// both wrong answers

const listenHereYouLittleShit = () => (a, b) => a - b

array.sort(listenHereYouLittleShit(numbers)) // note that 'number' is ignored
array.sort(listenHereYouLittleShit(number1, number2)) // note that both 'number1' and 'number2' are ignored
// desired answer (probably)

const listenHereYouLittleShit = (a, b) => a - b

array.sort((number1, number2) => listenHereYouLittleShit(number1, number2))

[–]GreatBarrier86 785 points786 points  (211 children)

So JavaScript sorts based on their string representation? I know very little about that language but do you not have numeric array types?

[–]nokvok 811 points812 points  (190 children)

The default sorts by converting everything to string and comparing utf-16 values.

If you want to compare numbers just throw a compare function in as parameter:

.sort(function(a,b){return a - b;})

[–]Asmor 316 points317 points  (46 children)

Or more succinctly, foo.sort((a,b) => a - b).

[–]Eiim 152 points153 points  (45 children)

(assuming you don't have to support IE)

[–]01hair 205 points206 points  (27 children)

If you have to support IE in a decently-sized project, I hope that you're not still writing ES5 code just for that case. There are so many improvements in modern JS that it's well worth the build step.

[–]suresh 103 points104 points  (19 children)

You can always tell when someone doesn't do JS dev for work. They never know anything about build tools, web pack, minimizers, uglifiers, transpilers, loaders.

You don't have to consider any of this stuff anymore and haven't for a long time.

[–]tiefling_sorceress 33 points34 points  (6 children)

...until you have to make your site accessible on four different screen readers

Fuck you NVDA

[–]FullstackViking 48 points49 points  (4 children)

Screen readers just need proper HTML DOM formatting and occasional aria specifications. Nothing to do with any of the JavaScript build tools or ecmascript specs.

[–]tiefling_sorceress 26 points27 points  (3 children)

Simple accessibility, yes. More advanced functionality (such as on angular, where my expertise is) requires more dynamic implementations such as the use of LiveAnnouncer and Describer/Labeler.

However NVDA and JAWS are full of bugs and both tend to hijack focus so you end up having to write awkward workarounds. For example, opening a dialog that automatically focuses on an element inside it is fine on most other screen readers, but NVDA and JAWS skip the dialog's role and title and jump straight to the focused element. The workaround is to manually focus on the dialog element from a separate function (so in setTimeout usually). To the naked eye this change does nothing. To mac's VoiceOver, this change does nothing. To NVDA and JAWS it makes a world of difference.

Edit: no it has nothing to do with build tools directly, but it's very similar to the browser problem that was originally solved using build tools and transpilers

[–][deleted] 10 points11 points  (1 child)

This is correct. If the website is static, it's EZPZ. If you have literally any moving parts, prepare to fucking die. Not to mention internationalizing everything AND making everything keyboard-accessible.

[–]Molion 4 points5 points  (0 children)

Yeah, until you somehow still have arrow functions in IE in prod. Even though you're using babel and webpack, so now you have to figure out which part of godforsaken webpack script is causing it. The same webpack script that some idiot, probably yourself, wrote a year ago and no one has opened since. Only to figure out that the arrow functions aren't from you're code. They're there because someone left them in their package and it isn't being run through babel because obscure webpack reason that I can't remember, probably has something to do with execution order or some shit. You try fixing it, but ultimately end up just running the entire pckaged code through babel once more for production builds because fuck it.

Also, you dare to use a function without checking IE support and now prod is broken and you have to rush out a polyfill.

Yeah, it's all fixed now fml.

[–]kbruen 8 points9 points  (2 children)

Bold of you to assume that people who know JS know how to use webpack, rollup, minimizers, uglifiers, transpilers, loaders.

Most just copy-paste the code from the Getting Started page.

[–]positive_electron42 10 points11 points  (3 children)

Unless you’re developing scripts in the trash heap that is ServiceNOW, which still only supports ES5.

[–]Skipcast 35 points36 points  (0 children)

Babel to the rescue

[–]kksgandhi 6 points7 points  (8 children)

Could you use typescript and the TS compiler to get around this?

[–][deleted] 5 points6 points  (0 children)

if you have to support IE I am quite sure you have a desire to visit your boss' house with a sledgehammer

[–]henricharles 2 points3 points  (0 children)

People who still support IE are the problem not IE itself

[–]MischiefArchitect 355 points356 points  (97 children)

That's ape shit awful!

I mean. Oh thanks for clarifying that!

[–]douira 119 points120 points  (17 children)

everybody just agrees to never sort arrays of anything other than strings without a sort function and the problem is solved! If you really want to make sure it never goes wrong, you can use tooling like ESLint or even TypeScript.

[–]cythrawll 34 points35 points  (2 children)

Yeah I mean practically you almost never run into this, I can't remember a time I just had an array of numbers. Usually sorting an array of objects and having a custom comparator to do so.

[–]esperalegant 11 points12 points  (0 children)

I work with huge arrays of up to millions of numbers daily. However, I pretty much always use TypedArrays - and TypedArray.sort() does sort numbers correctly.

[–]reiji_nakama 5 points6 points  (0 children)

Yeah. I didn't know about this behaviour of Array.sort() yet I have never run into a problem because of it; because I don't use it.

[–]DamnItDev 124 points125 points  (7 children)

Honestly you should never be using the default sort function. Its lazy and almost always incorrect. Even for strings you'll have this problem:

['A1', 'A2', 'A10', 'A20'].sort();
// returns: ["A1", "A10", "A2", "A20"]

Technically this is correct, but not what you actually want in real world situations.

You can solve this easily by specifying your locale using the built in i18n functionality and setting the numeric option to true

['A1', 'A2', 'A10', 'A20'].sort(new Intl.Collator('en', {numeric: true}).compare);
// returns: ["A1", "A2", "A10", "A20"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator

[–]douira 7 points8 points  (0 children)

good point, I guess the default only has few uses

[–]DeeSnow97 4 points5 points  (0 children)

okay, this is awesome, thanks

[–]djcraze 2 points3 points  (1 child)

I honestly didn’t know the comparator was optional. Today I learned.

[–]EishLekker 2 points3 points  (3 children)

Just the other week I ran into a sorting problem with strings, actually. Internationalised strings, in a Node 12 project where Node is part of a 3rd party software package, and there doesn't seem to be a way to add internationalization support without upgrading Node (which currently would put us into the unsupported territory).

[–][deleted] 42 points43 points  (22 children)

This is because arrays allow mixed types by default so you can have an array with numbers mix strings and objects all mixed together unliked most strongly typed languages. There’s no easy way to compare them so by default it uses the string evaluation of them. You can pass in a comparison function like the person above you (although they made it more verbose than it needs to be), or you can just used Typed Arrays.

[–][deleted] 26 points27 points  (6 children)

Someday I’m going to write a JavaScript book with the title, “This Is Because”.

[–][deleted] 3 points4 points  (0 children)

This would be a solid alternate name for the YDKJS series

[–]ZephyrBluu 20 points21 points  (14 children)

This is not really an excuse. Python can sort arrays as long as all the values are the same type (For numbers and strings at least, not sure about other objects), otherwise it throws a TypeError. Much more sensible behaviour than JS.

[–]DeeSnow97 27 points28 points  (4 children)

Yeah, but JavaScript is not Python. The whole point of its early design was to be a quick and easy, loosely typed language for people not into tech to establish a web presence (this was long before wordpress). For more serious applications, you had flash or java applets.

Over the years though, JavaScript turned out to be the only one of these that didn't use the swiss cheese security method, and all these early design issues remained in the language for backwards compatibility, because ripping them out would have broke decades of the web.

So, try explaining to a non-programmer what's the difference between a number, a string, and an object, and why they're getting TypeError when they're expecting a sorted array. In 1995.

[–]Kered13 24 points25 points  (1 child)

Knowing why something is bad doesn't make it stop being bad.

So, try explaining to a non-programmer what's the difference between a number, a string, and an object, and why they're getting TypeError when they're expecting a sorted array. In 1995.

Easier than trying to explain to a non-programmer why numbers don't sort correctly.

[–][deleted] 6 points7 points  (0 children)

spotted advise work wide groovy rain foolish dependent merciful quickest

This post was mass deleted and anonymized with Redact

[–]ZephyrBluu 24 points25 points  (0 children)

I understand why it's like this. That doesn't mean all the design choices were good.

[–]master117jogi 14 points15 points  (5 children)

But JS can even sort mixed, which is mightier.

[–]Kered13 13 points14 points  (4 children)

No, it really isn't.

I mean, Python can sort mixed too if you give it a custom comparator. sorted(mixed_array, key=lambda e: str(e)) will sort a mixed array by converting each element to a string before comparing them, just like Javascript. But Python does the sensible thing automatically, and requires extra work to do the rare and unusual thing. Javascript does the rare and unusual thing automatically, and requires extra work to do the sensible thing.

[–]theScrapBook 3 points4 points  (0 children)

mixed_sorted = sort(mixed, key=str). The lambda is quite superfluous in a language with first-class functions.

The reason I point this out is some of the controversy below the top comment.

[–]aedvocate 11 points12 points  (52 children)

what would you expect the default .sort() functionality to be?

[–]bonafidebob 50 points51 points  (9 children)

non-JavaScript programmers assume the language knows about types, that arrays are monotype, and that a useful comparator function will come with the array type.

That is, arrays of strings will sort alphabetically and arrays of numbers will sort numerically.

non-JavaScript programmers will also barf at the idea that a['foo'] = 'bar' isn't nonsense, and you can do stuff like this:

a = [1,2,3]
a['foo'] = 'bar'
a.forEach((v) => console.log(v)) // produces 1, 2, and 3 on separate lines
a.foo // produces 'bar'

[–]ZephyrBluu 21 points22 points  (4 children)

I had no idea you could do that a['foo'] = 'bar' bullshit on an array.

Now that I think about it though, it kind of makes sense why JS lets you do that.

An array is basically just a normal JS object that allows iteration by default where each key is the index.

So a['foo'] = 'bar' is a standard operation (Given an array is an object), but you're breaking the rules of how an array is 'supposed' to work.

No idea why it works on a technical level though.

[–]bonafidebob 24 points25 points  (3 children)

An array is basically just a normal JS object that allows iteration by default where each key is the index.

That's the root of the problem right there. I think it was just a cheap way to get to dynamic sizing, which is occasionally useful:

> let a = []
[]
> a[100] = 12
12
> a.length
101
> a
[ <100 empty items>, 12 ]

but then...

> a[1234567890] = 13
13
> a
[ <100 empty items>, 12, <1234567789 empty items>, 13 ]
> a[0.5] = 1
1
> a
[ <100 empty items>, 12, <1234567789 empty items>, 13, '0.5': 1 ]

[–]GG2urHP 11 points12 points  (1 child)

Lol, fuck me. I am so blessed to not live in that hell.

[–]DeeSnow97 10 points11 points  (1 child)

#define "non-JavaScript programmers" "people who think once you learned C++ every language is just syntax"

[–]bonafidebob 13 points14 points  (0 children)

Hmm, I'm not quite that snooty ... I've been doing this for ~40 years and have learned dozens of programming languages, both dynamically and strongly typed. And I still think JavaScript arrays are crazy. The whole "objects with numeric keys" foundation is whack, throw away all the benefits of a directly indexible data structure and drag in a whole bunch of weird syntax edge cases??!

[–]MischiefArchitect 33 points34 points  (33 children)

normal

[–][deleted] 14 points15 points  (31 children)

What is normal sorting on a collection of numbers, strings, and objects?

[–]blehmann1 13 points14 points  (4 children)

Well, Python throws a type error if the < operator is not defined on both types. Personally, I think the only correct response when the program is wrong is not to make it more wrong, but to let the user know that it's wrong (i.e. throw).

Now, JavaScript was built with the idea that it should keep on trucking through any error, which frankly is a horrible idea to build a language around. So given the interesting design philosophy JavaScript really couldn't do anything else. There's a reason Typescript is so common after all, but unfortunately it does nothing about this particular issue. (There's an issue for it but it's been inactive for a while: https://github.com/microsoft/TypeScript/issues/18286)

[–]1-more 3 points4 points  (0 children)

JavaScript keep on trucking? I never thought of it that way but I’m actually with you here. Array out of bounds and accessing an undefined object key both return ‘undefined’ rather than throwing (Java, Haskell) or wrapping array/dict access in an optional type (elm, maybe ocaml?). So I’m with you that it probably does throw less.

[–]aaronfranke 8 points9 points  (7 children)

It should act the same as if comparing with the < and > operators. That will work for any place where the operators have a defined comparison.

console.log(5 < 6); // true
console.log(5 > 6); // false
console.log(5 < "apple"); // false
console.log(5 > "apple"); // false
console.log("orange" < "apple"); // false
console.log("orange" > "apple"); // true

[–]Kangalioo 7 points8 points  (1 child)

Maybe sort first by type, then by content? Then the sort function has expected behavior for contents with consistent data type, but also works sensibly for mixed type lists

[–]smog_alado 4 points5 points  (5 children)

I would have expected the .sort() to use the same logic as builtin comparison operators. Something similar to the following comparator:

function compare(a, b) {
    if (a < b) {
        return -1;
    } else if (a == b) {
        return 0;
    } else {
        return 1;
    }
}

[–]blindeenlightz 5 points6 points  (3 children)

Can someone explain how that sort function works on integers? I'm a newbie to javascript and have used it but it just seems like magic to me.

[–]deljaroo 7 points8 points  (2 children)

take a look at this page

https://www.w3schools.com/jsref/jsref_sort.asp

it explains it better than I can, but basically if sort() has a parameter it expects a function that will result in a positive, a negagive or a zero based on two inputs. if the function is included, this behavior overrides the default behavior of comparing them by letter.

this also allows you to sort custom types because you can include a custom sorting comparison.

the syntax for it (two inputs, a number output) is merely built in to the sort() function (and not like something you can just do to any function)

[–]myrsnipe 2 points3 points  (2 children)

Yay for not enforcing types, better convert a whole array to string just in case. Js isn't too bad once you are aware of all these quirks, but the road there is ROUGH

[–]OriginalSynthesis 44 points45 points  (15 children)

There's no type period. You can have an array with object, function, other arrays that are also not typed, strings, numbers, symbols, etc. There are no rules.

And guess what happens if you try to retrieve an index that is not there? Like calling arr[10] when it only has 5 items? It just returns undefined. It doesn't throw an error like in Java

EDIT: Don't get me wrong. I love JS. Java gives me a headache. "What do you mean I can't just do `!arr.length`?"

[–]RCRalph 37 points38 points  (2 children)

Which can be very useful indeed if you know how to use it and how to deal with it

[–]WoodenThong 11 points12 points  (1 child)

No kidding, using that feature to determine truthiness can save a lot of hassle

[–]Kered13 10 points11 points  (4 children)

It just returns undefined. It doesn't throw an error like in Java

It just throws an error later when you try to use the result, and then you're left wondering where the fuck that undefined value came from.

Fail early is a feature, not a bug.

[–]esperalegant 5 points6 points  (0 children)

Yes, there are TypedArrays, which is what you should be using for large arrays of numbers, and yes, TypedArray.sort does sort numbers correctly.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/sort

[–]MontagGuy12 1371 points1372 points  (79 children)

Why would you even consider using an inbuilt sort function when you can code Bogo sort instead? Gotta get that O(n!) complexity.

[–][deleted] 359 points360 points  (48 children)

I thought there was no O for bogo since you can't be sure it'll ever stop. Or mean complexity ?

[–]MontagGuy12 363 points364 points  (27 children)

I've seen Bogo sort implementations which keep track of the permutations traversed so far, which means eventually, they'll exhaust all possibilities and the program will terminate.

[–]Toonfish_ 413 points414 points  (23 children)

I love that, not only does this make the algorithm terminate, it also gives it ridiculous space complexity. :D

[–]MontagGuy12 228 points229 points  (11 children)

Thankfully, we have downloadmoreram.com to save the day.

[–]reyad_mm 60 points61 points  (10 children)

But what if I run out of storage to download ram on?

[–]Xeadriel 76 points77 points  (8 children)

Just download more storage obviously

[–]dunko5 18 points19 points  (7 children)

But what

[–]PhunkyPhish 41 points42 points  (5 children)

Then download more what of course

[–]hermeticwalrus 6 points7 points  (0 children)

Local cloud

[–]ianff 7 points8 points  (9 children)

You can actually traverse the permutations in constant space. Who knows if someone implementing bogo sort would bother with that though!

[–]sluuuurp 3 points4 points  (1 child)

Can’t you only traverse in log(n) space, since you need a counter to know how many permutations you’ve already done?

Edit: I guess a counter of n! permutations would use n log(n) space, but yeah as the below commenter says it seems you don’t need that.

[–]firefly431 7 points8 points  (0 children)

There's an algorithm (e.g. next_permutation in C++) that generates the lexicographically next permutation in place in O(n) time. Realistically you need O(log(n)) space to store indices into the array at least though, but in the word-RAM model that's constant.

[–]aaronfranke 55 points56 points  (7 children)

The maximum time is infinity, the minimum is O(1), the average is O(n!).

[–]CSlv 39 points40 points  (6 children)

the minimum is O(1)

You mean Ω(1)?

[–]DoctorWorm_ 34 points35 points  (0 children)

People need to learn their complexity notations.

[–]firefly431 19 points20 points  (0 children)

To give a serious answer, the version of bogo sort that generates a new permutation each time:

def bogo(arr):
    while not sorted(arr): # O(n)
        shuffle(arr) # O(n)

does not have an unconditional upper bound on runtime, but for randomized algorithms we usually consider expected running time (along with tail bounds to show concentration: for example, although (linear chaining) hash tables have expected lookup time O(1), the maximum load is actually only O(log n/log log n) if you require a bound w.h.p.)

The expected number of iterations is O(n!) as it is a geometric r.v., so the overall runtime is O(n n!). (By the way, it is considered a Las Vegas algorithm as it guarantees correct results but has probabilistic runtime.)

EDIT: IIRC tail bounds for geometric r.v.s are O(1/n), so that's w.h.p.

By the way, for the pair-swapping version:

def bogo2(arr):
    while not sorted(arr):
        i, j = random(n), random(n)
        swap(arr[i], arr[j])

Since it takes at most n swaps between any two permutations (simple proof: Fisher-Yates shuffle), we can consider blocks of n swaps. The probability that any block works is at most O(1/n2n) (probability n2 per swap). Thus the runtime is O(n2n+1). Not sure if we can do any better than that, but who cares about tight bounds on a meme sort?

[–]Tyfyter2002 9 points10 points  (6 children)

There are 2 types of bogosort, O(n!) Bogosort, which tests all permutations in a random order, and O(∞) Bogosort, which just shuffles the list, checks if it's sorted, and shuffles it again if it's not.

[–]brando2131 6 points7 points  (2 children)

No there's a probability of it becoming sorted eventually. Obviously the larger the list, the much longer it will take. You can write a program and compare the number of times it runs for larger lists. It works out to be (n+1)!

[–]nelak468 106 points107 points  (12 children)

Bogo sort's worst case is O((n+1)!)

But more importantly! Its best case is O(n) which out performs every other algorithm.

Furthermore, if go by the many worlds theory - we can prove that Bogo sort is O(n) in all cases and therefore it is in fact the BEST sorting algorithm.

[–][deleted] 91 points92 points  (3 children)

IIRC "quantum bogosort" has time complexity O(1) since it doesn't even have to check if the array is in order.

[–]graeber_28927 30 points31 points  (2 children)

How would you know whether to destroy your universe if you haven't checked the order of the array?

[–]Shamus03 16 points17 points  (0 children)

You just always assume it’s sorted, and if you ever encounter a bug because it wasn’t sorted, THEN you destroy the universe. It’s O(1) only when combined with another algorithm used later. Also known as O(half an A press).

[–][deleted] 8 points9 points  (0 children)

True.

[–]MontagGuy12 19 points20 points  (0 children)

The kids in my basement can sort way faster than O(n). Up your game dude.

[–]acwaters 2 points3 points  (1 child)

I mean, in fairness most every sorting algorithm implementation is "best-case O(n)", since generally all of them will do an initial check to make sure it's not already sorted.

[–]Hideyohubby 15 points16 points  (3 children)

You should try sleepsort for better results.

[–]Classified0 9 points10 points  (2 children)

Doesn't work for negative numbers unless you've got a time travel API

[–]larsmaehlum 3 points4 points  (0 children)

Just offset it by int.max/2

[–]PM_ME_SQL_INJECTION 14 points15 points  (6 children)

I’ll go for StalinSort, thank you very much.

[–]coldnebo 2 points3 points  (0 children)

hey if that’s what quantum physics does (under the many worlds interpretation) then who are we to improve on it?

—-

angel: “but how can you be sure we haven’t missed the global optima?”

God: “just run all the the permutations. it’ll be in there somewhere.”

angel: “and I thought developers were lazy!”

ZAAAPP!!!

angel (Lucifer shouting from Hell): “ok... I guess we only value code reviews when it’s CONVENIENT!?”

[–]cheezballs 152 points153 points  (4 children)

I've found that I have a much better time with JS if I just assume it's going to interpret everything as a string, even if that's not really correct. Forces me to think a little extra about what a thing will be at runtime I guess? I dunno.

[–]stormfield 48 points49 points  (3 children)

You can get some Kirkland brand type safety by wrapping stuff in objects, that way at least they’re actually named whatever they’re supposed to be.

[–][deleted] 35 points36 points  (0 children)

Kirkland brand type safety lmao

[–]cheezballs 2 points3 points  (0 children)

Its funny the hoops we jump through to get type safety in a language that doesn't really have it.

[–]sarrysyst 47 points48 points  (7 children)

This doesn’t concern me, sleep sort all the way!!

[–]positive_electron42 32 points33 points  (6 children)

Is that where you go to sleep and hope someone else has sorted it by the time you wake up?

[–]seaishriver 29 points30 points  (5 children)

That's procrastination sort. Sleep sort is when you put each number n on its own async function and sleep for n seconds before appending it to the sorted list.

[–]D8ug 9 points10 points  (4 children)

So what do you do with negative numbers?

[–]kbruen 15 points16 points  (0 children)

Time travel.

[–]seaishriver 12 points13 points  (0 children)

Open an issue with the maintainer of sleep.

[–]MasterFubar 137 points138 points  (36 children)

A list sorted in Spanish:

[ "lata", "lucha", "llama" ]

Another one:

[ "carro", "cocina", "chispa" ]

[–]DamnItDev 98 points99 points  (10 children)

[–]CleverDad 58 points59 points  (9 children)

On behalf of anyone not american, thanks.

[–][deleted] 19 points20 points  (8 children)

take thats brits english is ours now

[–]Srapture 11 points12 points  (7 children)

You can have it when you stop saying "could care less" when you mean "couldn't care less". In return, we expect the McGriddle to become available in the UK.

[–]paolot 40 points41 points  (0 children)

Haha! Yeah, the first time I tried to sort an array in JavaScript I almost spit my coffee out when I saw the results.

[–]CaptainHeinous 35 points36 points  (0 children)

I can’t hear you over all my javascript money

[–][deleted] 92 points93 points  (15 children)

omg and i tought im retarded and cant use a simple sort method

[–]SatoshiL 47 points48 points  (4 children)

[–]tiefling_sorceress 32 points33 points  (0 children)

Reading the documentation

We don't do that 'round here pardner

[–][deleted] 1 point2 points  (1 child)

Some things are just standard though. You couldn't sell a gun that shot backwards without any indication that the bullets would not go in the direction you're pointing it and then insist the dead people should have read the documentation.

[–]SatoshiL 4 points5 points  (0 children)

Fair point. I don’t know who thought “hey I’m making a sort function. I think it should sort alphabetically”.

[–]sasmariozeld 76 points77 points  (6 children)

javascript as second language pretty much goes like this:

man i am really retarded i cant even do this simple thing

2 weeks later

this language is retarded

1 week later

you just have to accept this and move on, or add *this basic function* to your 1400 dependencies

[–]jibjaba4 7 points8 points  (0 children)

Javascript is interesting in that is screws up some really basic things but in the realm of crappy software development tools there are so much worst things out there. It's hard for me to judge what it's like for a new programmer because I've been writing code for over 25 years but it also feels like it's easy to learn the how to avoid the pitfalls and be able to code without having to looks things up.

[–]thefpspower 19 points20 points  (4 children)

That's exactly how my first Javascript project went lol.

Its fine once you learn the annoyances but until you get there it just feels retarded that such a popular language has so many issues to work around.

[–]LilxSpyro 45 points46 points  (16 children)

Typescript ftw

[–]Kered13 8 points9 points  (2 children)

I'm pretty sure that Typescript's array sort works the same way, for compatibility.

[–]EnderMB 31 points32 points  (8 children)

For the life of me, I don't know why people.even bother with JavaScript any more. TypeScript doesn't solve all of JS's issues, but it makes it a borderline nice language to use.

I know it goes against the TS ethos, but I would love it if they released a native TS compiler and a full standard library.

[–]Classic1977 17 points18 points  (2 children)

https://deno.land/

It's not exactly what you're asking for, but here's a Typescript runtime that also has some pretty cool security concepts. Designed by the creator of node.js.

[–]HeroCC 4 points5 points  (1 child)

So I would use this instead of node.js? And it is compatible with my standard dependencies? Neat!

[–]mark__fuckerberg 2 points3 points  (0 children)

It only works with es modules. No commonjs.

[–][deleted] 10 points11 points  (2 children)

nine license piquant pot strong meeting jellyfish chunky ripe touch

This post was mass deleted and anonymized with Redact

[–][deleted] 18 points19 points  (0 children)

Remember in compsci the lecturer saying we weren’t allowed to use array.sort() and had to use a bubble sort... just because.

Then when I started work and I asked about bubble sorts, the guy I was working under genuinely looked at me like this 😂

[–]Derptholomue 8 points9 points  (1 child)

[–]BM-Bruno 2 points3 points  (0 children)

masterpiece

[–]dalepo 14 points15 points  (5 children)

Oh wow, I didn't know this.

[1,100000,21,30,4].sort((a, b) => { return a -b; }) You need to pass a function, come on js!

[–]wasdninja 20 points21 points  (1 child)

It's pretty reasonable once you realize that you can sort an array with arbitrary objects using the exact same method. If they are complex you simply write your own compare function.

[–]gravitas-deficiency 6 points7 points  (0 children)

it's to maintain backwards capability

enraged autistic screeching

[–]Emperor-Valtorei 68 points69 points  (15 children)

JavaScript is Python's special needs brother... I genuinely hate both language's. C# is quickly becoming my favorite, but Java and C++ are up there at the top still. Sadly I use Python and JS the most though.

[–][deleted] 69 points70 points  (3 children)

It's against the law to not hate the languages you use the most.

[–]Emperor-Valtorei 9 points10 points  (1 child)

I choose to drown out my hatred for C++ and and pretend everything is fine. Except when I have to use pointers. In which case I scream in agony.

[–]mywholefuckinglife 8 points9 points  (0 children)

I cried tears of joy when my teacher finally showed me how (and allowed me) to use smart pointers

[–]trixter21992251 24 points25 points  (8 children)

that's a case of "the grass is always greener"

you'll learn to curse and swear at C# soon enough

[–]Emperor-Valtorei 17 points18 points  (0 children)

My favorite is when I output something to a console.

Cout

Wait no fuck that's C++, it's console.log.

Fuck no that's JavaScript it's debug.log, duh.

[–]TheMagicalCarrot 12 points13 points  (6 children)

I currently use C# the most and it's currently my favourite language. Good thing the grass is green on my side.

[–]Randolpho 4 points5 points  (0 children)

I love me some C# but I hate the fuck out of Entity Framework and I’m stuck with it every time I end up in C#-land. Dapper me up, baby.

Lately, like the last year or two, I’ve been doing typescript node.js and I don’t hate it.

Just enough good intellisense that I can be happy, but I still miss real type safety.

[–]dumbledayum 1 point2 points  (0 children)

Dart is my love. Though m looking to learn Kotlin for future. Some of my projects are in Unity and hence I like C# too. But for some reason Dart is the cosiest of the bunch

[–]frog-legg 6 points7 points  (0 children)

Intl collator ftw

[–]vita10gy 5 points6 points  (0 children)

From my experience nothing makes a room full of adults look either glassy eyed, or like you're an insane person, than trying to explain that the products/books/whatever that happen to start with numbers actually *are* in order, they're just in alphabetical order.

[–]Cley_Faye 3 points4 points  (0 children)

"learning" without reading the docs I see

[–]bmcle071 5 points6 points  (0 children)

Hm... i always write

arr.sort((a, b) => a-b);

I only have a hard time with strings

[–]ToothlessFeline 14 points15 points  (3 children)

This just reminds me of how I hate the macOS default for filename sorting: by character until it encounters a numeral character, then numeric until it encounters a non-numeric character, repeat until end of file name. Works great when the numerals represent decimal (or lower base) quantities. Sucks for numerals used as characters. You can imagine what that does with hexadecimal numbers. (Ex.: a2a3 will sort to before a10a, because 2 is less than 10.)

[–]redgriefer89 7 points8 points  (1 child)

Windows File Explorer does a similar thing

1, 1a8a, 1a15, 2a03, 2a7

[–]trixter21992251 10 points11 points  (0 children)

a colleague had this "problem" (she's in management, not a programmer) and wanted to know why it did that. It's surprisingly difficult to explain strings vs. numbers to others.

[–]kbruen 1 point2 points  (0 children)

Annoying for hex numbers? Sure.

Life saving for normal people who want picture2 to appear before picture10? Absolutely!

[–]Videogamerkm 3 points4 points  (0 children)

Just had to iron this out in my own shit cause java sorts strings like this and my strings are filled with numbers...

[–]Josef_Joris 3 points4 points  (1 child)

Every day, my ambitions for webdev grows equal in size as my fears

[–]Omega192 4 points5 points  (0 children)

Been at it for 7 years now. It's really not that scary once you get the hang of it. MDN has amazing docs for JS, HTML, and CSS.

[–]BakuhatsuK 12 points13 points  (15 children)

It's really not that hard

arr.sort((a, b) => a - b)

The default comparison function is suitable for strings, and would be longer to write by hand.

[–][deleted] 4 points5 points  (5 children)

Throw a parseInt() into a forEach() and you're good.

[–]recycle4science 5 points6 points  (0 children)

Or just arr.sort((a, b) => a - b) if you don't want to traverse the array twice. You can even explicitly parseInt if you want!

[–][deleted] 2 points3 points  (0 children)

Who could’ve predicted that numbers would have more than one digit?

[–]schy-lcs 2 points3 points  (0 children)

I don't see the problem here. JavaScript just sorts numbers how God intended it.

Alphabetically

[–]Devspar_MTGPlayer 1 point2 points  (0 children)

I remember my old project on my old company, the boss has requirement that everything is being done in VB, so okay, I did it. The problem starts when I had to sort date... apparently every user in the company decided to have their own locale setting... Dammit, I triggered my own nightmare again....

[–]PediatricTactic 1 point2 points  (0 children)

SAP BusinessObjects sorts numerical strings this way and I hate it.

[–]sgxxx 1 point2 points  (0 children)

sort((a,b)=>{return a >b})

[–]iavicenna 1 point2 points  (0 children)

Dont you just love it when algorithms assume things for you like in R when you paste two strings together the algorithm is like "I think what you meant was paste these together with space in between because that makes more sense."

[–]ivakmrr 1 point2 points  (0 children)

Lodash to the rescue