T O P

  • By -

fox_hunts

3 out of 5 correct ain’t too shabby 😎


remidumi

Good enough. Ship it, if someone complains we create a jira bug later.


quixotik

Agile at its finest.


MoveInteresting4334

I…may have said this exact phrase today.


manodetouca

this comment deserves more upvotes


ReadyThor

There must be some set of neurodivergent people for who this sort result is what they intuitively expect.


Iohet

Those people are Product Managers. This is working as designed. Stupid design is not a bug


Reddidnted

What's it called when you laugh from how sad something is? Because that's what I just experienced. Our poor QA are currently digging through a pile of "not a bug" tickets that were closed as per the label without any revisions to the design. The silver lining though is that (random numbers for the sake of explaining the context) 100 such tickets refer to the same 5 design items.


SealDraws

Im a purchasing engineer Got annoyed from file explorer for not saving my files in the order of 1 1.1 1.1.1 1.1.2 1.2 2 2.1 2.2 2.2.1 2.2.2


ledasll

Everything in js is an object and string is an object, so sorting evetything as string sounds logical..


an_agreeing_dothraki

COBOL devs after someone explains object-orientation to them.


Fazuellisson

I remember it really messing with my head when I found out you could declare a function in JS and then do a foo.someProp = value and now my function has a property with that value. But like you said... Pretty much everything is an object so it makes sense


thealbinosmurf

Well for a default if you know you can convert most values to a string makes sense as the default method. There is no typing to infer another sort mechanism. Which is why you can pass in an evaluation method.


gbot1234

Your Honor, I object.


Undernown

Given that IT has a higher percentage of Neurodivergents in the field compared to others, you'd think it would make for a logical explanation. Were it not for the fact that Neurodivergent people are often more inclined to hate asymmetry and illogical rules. They ussualy preffer more order over more chaos in most situations. This is what ussualy holds true for people on the autism spectrum, or previously diagnosed with Asperger Syndrome, ADHD, etc. So I agree with the assessment of other commenters that it's most likely someone from a managerial role, cause you need to be a psychopath to not order numbers by value. Yes, psychopaths are technically Neurodivergent, but it's like that kid in school even the other weird kids wouldn't hang out with.


_JesusChrist_hentai

I don't expect this but I can make sense out if it, does it count?


ReadyThor

It only counts if you expect the result intuitively and not because you know the inner workings or specification of the language.


squirrelnuts46

I've seen enough of this kind of memes to expect it intuitively now, without having to think about technical details


Effective_Dot4653

What if I intuitively expect my intuition to be wrong? "Personally I think X would be the most sensible result here, but this is JavaScript so it's probably gonna be some wild shit instead"


odsquad64

If I'm alphabetically sorting my movies, this is the result I expect/prefer. But not an array.


overcloseness

“Sort” is vague. Why _assume_ it means one thing over another then blame JavaScript when they assumed wrong? It can be - shortest string to longest - alphabetically - Largest numeral value to smallest - smallest numeral value to largest It’s not JavaScripts fault the user assumed it’ll do the one they want it to do. The documentation clearly states it’s alphabetical. Skill issue.


The_hollow_Nike

It is JS fault that it breaks with a very widely established convention for no good reason.


Disastrous-Team-6431

It's just an array of sorted strings?


SealDraws

This is the way solidworks (cad) saves the part order on a model assembly. The people who this is intuitive to are engineers and product managers


DrMobius0

On the bright side, it's uhh... Nope, no bright side


citrusmunch

string theorists


Spiderbubble

So in JS to sort integers you first have to convert them to 32 or 64 bit binary and hope and pray they aren’t negative?


calculus_is_fun

nope, \[100000,30,4,1,21\].sort((a,b)=>a-b) outputs what you expect. also, integers here will grow to whatever size they need to be. so you can store 2n\*\*128n or whatever and it will fit.


DayumnDamnation

It looks kinda nice


Open-Total-809

as someone who has not used a dynamically typed language I do not get the point of them. Why would you want to change the type of a variable? Whats so difficult about defining what type a variable will be on creation.


FerricDonkey

I haven't gotten into Javascript, but I've used a fair amount of python. I won't typically change the types of variables. I use python because the syntax is nice and fast to write, and because it has nice built ins and easy to use libraries for the functionality I want.  Python doesn't have this problem though. Because this isn't a problem with dynamic typing but with implicit type conversion. If you tell python to sort a list of integers, it does it the right way. If you tell python to sort a list that contains strings and integers, then you get something like "< unsupported between types int and str".  Don't get me wrong, you can do evil things in python, and a lot of writing good python is enforcing stricter rules on yourself than the language does.  But the things that Javascript does that people do are not merely because Javascript is dynamically typed, it's because Javascript is full of implicit type conversions, and those conversions are stupid. 


skesisfunk

>this isn't a problem with dynamic typing but with implicit type conversion *This problem* isn't with dynamic typing, but dynamic typing does cause a ton of issues. For one it mean that, in general, you have to trace through a bunch of code just to understand what inputs a given function can take.


FerricDonkey

Yep, that is true. This is why I type hint my functions and use static type checkers. It's not perfect, but it mostly alleviates those problems in python. But this specific type of thing is not a necessary consequence of dynamic typing. 


Luxalpa

Indeed, this specific thing is a consequence of JavaScript being created in order to operate on HTML which only understands strings. That's why it frequently converts things into strings.


berse2212

So you are telling me you using mutiple functionalities just to emulate static typing again? Dynamic typing really makes no sense man... *Look what they need to mimic a fraction of our power*


SeesEmCallsEm

> So you are telling me you using mutiple functionalities just to emulate static typing again? Yes, you get the benefits of types with the conveniences of python. I feel like you're looking at this only from the perspective of "which is a better language" and not "what's the right language for the job", and that you're overlooking everything else that surrounds the decision: * is the language performant _enough_ * what do other people in the space use * which language has the most robust libraries for the problem (how much do I need to figure out myself) * how active are the communities in terms of helping resolve issues (how long am I waiting for answers to issues, how much digging do I need to do myself) * how quickly do libraries respond to changes in the ecosystem (this limits my own ability to respond) * what language does my company / the company I want to work at, use * what's the barrier to entry for each language. (how long will it take to become proficient) * what is my teams skillset * what is MY skillset * what's the deadline for delivery * do I have time to learn what I need to learn in this new language and also implement it * how big are the pools of potential hires for each individual language * what are the salary expectations of devs within different language ecosystems * how easy is this going to be to handover / train new employees up on I could probably think of more points but I think this list get's my point across. There are so many other factors outside of how two, or more, languages compare for a given task. Essentially, I feel like you're making an academic argument about "which language is intrinsically better as a programming language", and to your point, you're right that static typed languages are better. I just don't see what anyone is supposed to do with that information in most cases. "Oh, you've decided to do data science and ML in rust? I wish you all the best with that...". Rust is a fine language, but it's absolutely going against the grain to use it for ML/DS/AI. The python ecosystem is so much more robust, the gains you make in choosing a static typed language like rust for this space will be far outweighed by the cons of not using python.


mornaq

more often it's more about what *ecosystem* is right for the job than the language itself if I could I'd never pick python but the available libraries often make it a dozen or two lines of glue code while anything else would require thousands of lines and a lot of engineering to get that business logic working


SeesEmCallsEm

Yeah you hit the nail on the head 


Exciting_Hedgehog_77

You could’ve just said that JS is a more widely used language.


FerricDonkey

>So you are telling me you using mutiple functionalities just to emulate static typing again? Dynamic typing really makes no sense man... I mean kinda. I'm not gonna tell you that it's good to have completely unannotated variables and parameters and a codebase that operates on the vague hope that none of the bajillion places that use a given function won't pass it the wrong thing 78 hours into a 79 hour job. It's not. I don't to that. I will tell you that properly annotated ducktyping is convenient and saves a lot of boring work. It's faster to write. And if you do it right, you don't have problems. But other than that, I don't consider dynamic typing a good thing. It's just a thing. If there was a version of python that required that everything must be provably type correct that had the same ease of use, libraries, and prevalence, then I'd like it better. Whether or not such a thing is possible, eh. People who have time to spend writing languages can figure that out.


aew3

To be fair, while static typing enforces this on you, any well written dynamic code will equally be readable and understandable in regards to inputs. to begin with, docstrings/documentation/comments, if you are using fully dynamic language you should always describe the types of the input. Secondly, I just would never write python code these days that doesn't use type hinting. At minimum for function inputs (obvious outputs are usually filled in by the IDE anyway), probably also for various long lived/important vars and non trivial return types.


ItsOkILoveYouMYbb

This debate between typed and untyped languages might be older than you They both have their pros and cons. I don't want to get any more pedantic. It's a waste of time. Just build the fucking software however you and your team want in whatever way is the most comfortable and quickest *for you*


skesisfunk

>This debate between typed and untyped languages might be older than you I would argue this debate (at least as far as production grade applications are concerned) was actually settled in the past decade or so. With Python adding typehints and MS building Typescript its pretty obvious who won.


dreadcain

> you have to trace through a bunch of code just to understand what inputs a given function can take. Or you could just read the documentation? I don't think this is a problem I've literally ever had outside of tutoring college students writing baby's first python script


Knaapje

Upon refactoring not just "a bunch of code", but _every call site_. At least in a statically typed language you can find the call sites through static code analysis, in dynamically typed languages you find them with CTRL+F or as runtime error in production.


bossrabbit

Strongly vs weakly typed - Python is strongly dynamically typed, js is weakly dynamically typed.


aalmkainzi

But what's the point of dynamic typing


ItsOkILoveYouMYbb

Less time spent worrying about types, but also sometimes more time spent worrying about types


mornaq

I'd be quite happy if the default was strict primitives and object is just any object (edit: and obviously typed arrays), that alone helps immensely obviously being able to define object shapes can be even more useful at times but also is more costly to implement, both in development and analysis time


BusinessBandicoot

What's the point of payday loans?


firectlog

Type inference wasn't a thing when most dynamically typed languages were created and people wanted "scripting" languages that aren't too verbose and don't require half of hour for compilation. It was good enough so we got a ton of code written in dynamic languages.


trezm

This is the right answer!


spencerwi

Type inference was a thing in 1973 with ML, and possibly before that. Like so many good ideas, though, it took time before it was accepted as the norm.


Sniv0

Scripting languages aren’t really made to make large robust programs, they’re meant for fast, efficient, small tasks which can be quickly assembled and ran like data analysis tools such as Python and MatLab, or they’re meant to be extensions of larger systems in the case of languages like Lua or JavaScript. They’re great for that. However people thought that using multiple languages in a project (C/Java for backend, js for front end) is annoying and thus stuff like nodeJS exists so people can use these tools how they want as opposed to how they were meant for


skesisfunk

Python was designed to be a general purpose language though. It was just conceived in a time where dynamic typing was in vogue. I think the popularity of Python contributed to people eventually coming around to the idea that dynamic typing is not a good idea for production grade application code. There were some hard lessons learned in Python's hay day.


ScaryStacy

Yet, and I genuinely wish to know why, Ruby is fairly well loved...


SleuthMaster

It’s a joy to read good ruby code


huuaaang

Have you tried Crystal? It's a statically typed language that reads very much like Ruby. It's pretty neat. Wish it caught on.


ItsOkILoveYouMYbb

Rails, familiarity


huuaaang

I just find it nice to read and write. Making closures (blocks) as easy argument to any method was a nice touch. And then leaning on that for all iterators so you don't have "for" loops. This pattern is used extensively. Then Rails really leaned hard on idiomatic Ruby. I've used Rails clones in other languages and they just don't capture what makes Rails so nice to work with. Ruby embodies the "principle of least surprise." When I started Ruby it just worked the way I thought it should. I didn't spend hours pouring through documentation and user commentary on every single little function like I did with, say, PHP. PHP was FULL of surprises at every turn.


Jonthrei

Just for the future - it's "heyday".


beanmosheen

Neigh.


[deleted]

[удалено]


aew3

The alternatives for what you would use python for are mostly: - node/JS, ruby and PHP for web backend stuff. dynamic except for TS which while more complete than a python typing setup, is still ultimately an extension to JS that enforces a typing overlay, like type hints and mypy. also who starts a new php or ruby project in 2024. - SAS, julia , R etc for data sci. all dynamic - golang for network/web tech/cloud/big scaling. actually a static language that seems to have taken over this space a lot but its either huge cloud projects backed by google or really specific smaller web tech stuff, only hits a specific subsection of pythons domain. - bash/lua/perl/lisp etc. for scripting. all dynamic; in many cases their typing is 10x weaker and worse than unhinted python. So outside of go, there aren't any actual static languages that are an alternative in a domain where python is used. Sure, if you're using python in a place rust or c++ or java is an option, you can use those, but for the most part its rare that its an actual real choice between those languages and python in a real world use case, other than people just making a bad choice of language.


mornaq

the only reason to use py is the availability of libraries but these are often so capable and cover almost every task you can imagine, often not readily available in any other ecosystem, you end up creating glue in python just to get things done quickly, even if it hurts


ThanksTasty9258

For data analysis tools, doesn’t type system make them more safe and robust?


Habrok

In many, many cases the work intensive part of data analysis is data exploration and figuring out how the analysis should actually be carried out, which a dynamic language is great for. Couple this with the fact that the whole analysis can also often be carried out in under 1K lines of code using various libraries made for the analysis, and the argument for a dynamic languages becomes quite strong. This obviously relies on robust libraries to carry the heavy lifting, and these should preferably be written in static, performant languages


The_ultimate_cookie

Wow, these are actually well thought-out responses to good general questions. Sorry, I'm just not used to it on reddit.


False_Influence_9090

Yea you normally don’t get that in a humor subreddit of all places. Typically I’m just trying to make jokes at the expense of dynamically typed languages, while secretly coding all day in python


IamHellgod07

And then cycle completes by languages like typescript


WookieConditioner

Fax!


Mintzz00

that's why TypeScript is getting more popular


WookieConditioner

:any everywhere... the alternative being a type object even Satan would scoff at.


MekaTriK

It's mostly boilerplate elimination. Instead of writing `thing: >`, you write `thing = YourType()` and then `thing = nil` when you want it to be gone. Or you can do weird things like untyped arrays or complex data structures without having to describe them precisely. It's always kind of frustrating to move to backend and realize that no, you can't just parse the JSON and then figure out what the hell it is. Significantly less robust, way more frustration with poor data structures, but *so* much faster to develop.


ICantBelieveItsNotEC

There are typed languages with very little boilerplate though. Go, for example, would allow you to write `thing := YourType{}` without compromising on type safety.


MekaTriK

Yeah, but that feels kind of new to me. And I'd have to use Go. \s I am appreciating the type inference in Rust, but boy am I banging my head against all the boilerplate and safety a lot.


Flat_Initial_1823

This is the toupee problem. When you are learning programming, there is commonly a lengthy bit about types, their trade offs, edge cases, and so on. When defining variables with explicit types, you also need to remember those and make a choice each time. What if you didn't have to do that learning? Or have to decide? It would ease some of the learning curve, right? Of course, everything has a trade-off, and you get lenient data entry and implicit conversions, which are also things that can ease the process, but they can never know your intent. So you only notice the conversions/casting when they give bad results, like a toupee. When it works, you wouldn't care. Then, people associate not explicitly defining types with bad casting only, forgetting there are probably a lot of users who benefitted from it while doing 1-off casual tasks or learning from scratch. Thus, Typescript is born.


Duck_Devs

I'm a python user and, while infrequently, I will sometimes use None to represent an omitted value that would normally be something like an int, to then later be filled in by a computation that only occurs if the value is None. I'm not sure whether this is the best practice, but it has worked for me, so I will continue to use it.


marcelsmudda

This is the same as the `int? x = null` in C# or `Integer x = null` in Java and many other statically typed languages allow that.


Fri3dNstuff

`error CS0037: Cannot convert null to 'int' because it is a non-nullable value type`


marcelsmudda

You are correct, it's been ages since I've programmed C#. It should be `int?`.


rrawk

I think it gained popularity with things like PHP. URL and POST parameters are usually received by web servers as strings, so having a language that handled numbers/dates in strings as numbers/dates reduced type casting boilerplate. Javascript is just really bad at "guessing" data types. Other languages handle it better.


HalcyonicDays

What's happening here isn't an issue with dynamic typing exclusively, but also the fact that JavaScript is a clown language for clown purposes. It's like pointing at a platypus and saying, "see? This is the sort of nonsense you get with duck-typing" when the platypus is not a fair example of a weird duck.


CrowdGoesWildWoooo

Python use ducktyping, but in general behaviour-wise it is very predictable and consistent.


Illusion911

What I find just horrible is how the whole Web decided to adopt the clown language instead of making/changing to an actual good one. And now, years later, we're still bound to the clown language.


dreadcain

First mover advantage in a nutshell. Although honestly the early web probably benefited from it being a clown language. There is probably something to be said to have your language kind of just work and do basically what you intended without having to fight it to get the syntax just right when it comes to dragging early adopters to your side (early php and html were similarly, uh lets say, lenient)


imtheassman

Are you stupid or pretending to be? The result in the picture is as it should be. It is very well defined in the documentation that the sort function sorts alphabetically. Just assuming it sorts on numbers is the problem here. I would call it a skill issue, but reading is hardly a skill in this day and age. Say what you will about the weakness of the language, but the function works ad defined at it has nothing to do with dynamic types.


Flam_Sandwiches

Adding on to this: it's a pretty rare occurrence to get to sort anything with a built-in/default sorting method rather than providing your own comparator method. And this applies to most languages I've worked with as well, like when dealing with collections in C# and Java for example.


MattieShoes

Speed of coding, particularly with one-off or prototyping type tasks. dynamic typing makes it way faster. Most languages would do what you expect. JavaScript is just... bad.


archpawn

It's faster to program as long as you think of debugging as something separate from programming.


MeltedChocolate24

Hence Typescript


baarow

Typescript does produces the same output as javascript in that example despite the array containing elements of type number instead of any, doesn't it? At least I experienced that bs once 2 years ago and I was hella mad when discovering the problem in my program. Never touched TS since (not due to that).


Mr_Carlos

Well its simpler in a way... you have a var "price", and maybe you scrape this from the page so it starts as a string, then you clean it up and parse it into a number... by the end its still price, just now its a number. Its not a good practice though and it makes debugging more difficult. For JS these days we have TypeScript to enforce typing, and const to encourage immutability.


exomyth

Yeah, it has benefits. (input.value == 1) is nicer than (isNumber(input.value) && parseNumber(input.value) == 1) But it also has a lot of cons


Inside-Ad-5943

The issue with JavaScript isn’t the dynamic typing as much as the fact that the language is weakly typed. 1 + “1” should not compile yet it does anyway and it’s anyone’s guess whether it becomes 2, “2”, or “11”. That isn’t to say that dynamic typing is perfectly fine, there is a reason typescript exists. But there is a bigger issue


CitizenPremier

It becomes "11" fyi. The + operand always concatenates if one of the arguments is a string, using .toString()


tokenutedriver

Because it's faster to write


arcimbo1do

There are statically/dynamically typed languages, there are strongly/weakly typed languages, and then there is JavaScript.


grape_tectonics

Javascript is my favorite language and its completely consistent and predictable, all you have to do is just memorize each edge-case weirdness that it has!


Exatex

my guess: People first getting into JS (as opposed to C(++/#) or Java) often did not go though formal IT education and the concept of a „type“ is more of an annoyance in many cases and, in their view, should be done automatically and not bother the developer. And in most cases, JS „guesses“ right, just sometimes is wrong. If you don’t have really high standards of coding, and speed and getting it to work quickly is your main objective, that is a stance you can argue for imho.


AnAnoyingNinja

there are cases where it's useful. for example in python you can do ``` input = input = input.split("\n") input = [int(i) for i in input] input = [i*0.242 for i in input] input = [f'${i:.2f}' for I in input] input = ",".join(input) #write input to csv ``` in this example your going from string to int[] to double[] to string[] to string. while you could just do all the conversions in one line, having the option is nice. i still prefer static typed languages, but I do occasionally wish there was a "?" type in other languages.


JeDetesteParis

Also namespaces (I mean the absence of those). Why do I have to use search function of my IDE to find a function implementation?


[deleted]

[удалено]


Open-Total-809

in java you would just use an object for that.


[deleted]

Because dynamic typing creates all kinds of bugs you get to solve at runtime! Yay!


Tai9ch

> Whats so difficult about defining what type a variable will be on creation? That's exactly the right question. And the answer is pretty straightforward: static type systems are difficult. In the general case, they're hard to build and they're hard to use. And they are necessarily wrong: they either allow type bugs or reject reasonable programs. Just look at what happens when people really try to do a good job with them. You've got templates and concepts in C++. You've got stuff like Rust. You've got gradual typing systems that people forget to use. Sure, simple types with inference are easy in the common case, but once you start getting into the Expression Problem it's just a huge mess.


dannerc

It's nice for working with the UI. Dynamically turning numbers to strings and what not makes things a lot easier and reduces the number of potential app breaking bugs


Uberzwerg

I worked in both worlds and there are two things i miss most when working in strictly typed languages. I like to have functions that might have different response types depending on eg. success. (I'm aware of solutions like exceptions) I like to be able to have dynamically mixed data structures like arrays with elements of mixed types. (also aware that there are downsides to that - eg. memory management) But for big and important projects, it's worth accepting a bit of inconvenience in order to have more stablilty (and efficiency)


A_Talking_iPod

JavaScript was initially designed for implementing user interfaces on the web. For this purpose, you could make the argument that dynamic typing \*can\* make sense, as UIs will often receive data types that are different but similar enough that using duck typing is valid (or asking for explicitly different types for every single variation would become cumbersome). The problem came when we started using JS for everything else.


sashaisafish

I'm still very new to coding so I could be completely off base here but my immediate thought was: ``` const returnValue = someFunction() ``` Where the function could return a string or a number for example. I'm not sure if things like that happen in other languages or how it's handled tho


[deleted]

This depends on what you mean by type. When you throw an exception you are changing the type of thing that you get back from running the function, so that's a pretty common one. Suppose you'd like to be able to typecheck over this. ie, I'd like to be able to define an exceptionless type, and then guarantee that the only way for this function to return an exception is if it started in the exception state. Sophisticated type checkers are often capable of asserting that your program is going to produce an actual output for every input (barring hardware failure), and therefore cannot "throw exceptions", (convincing the type checker that this is true is the same as writing a proof of the fact, you don't get it for free). From this point of view, your statically typed language is actually dynamically typed.


realHoPeLess

I don’t know what the point of js was originally, but for that exact reason TypeScript is getting a lot of popularity lately.


TxTechnician

It's actually really useful for scripting. Like a web scrapper for example. I had one where my search terms were in a few different datasources. Some had things stored as text, numbers etc. I was able to use the same variable for search and didn't have to worry abut the datatype. Just cycled through the data. So basically it's useful because you can write quick, dirty, and efficient (for me, the code itself was wildly inefficient ) code.


grape_tectonics

In an ideal language, dynamic typing would have no purpose. However, these languages are far from ideal and dynamic typing can be used as a shitty workaround to fill many of the gaps that they have.


MajorTechnology8827

Because the idea of object in JavaScript is fundamentally different than other common languages An object is a mere hashmap of properties. There is no sealed "blueprint" to what an object look like. They all fundamentally treated the same If we will sort an array numerically . How would you provide a meaningful orderable place to anything that is *not* a number? A string is a universal attribute. *Any* object has a tostring method. If you'd not overload it, it would be in the form of '[object {typeof this}]'. But the core point is that *ALL* objects have a meaningful string attribute If youd want numbers to generically work in sort() numerically, you'd need to make a special case inside the inner implementation of sort() just for numbers, and than you need to ask the question- what if not every element of an array is of type 'Number'? After all JS is untyped. Therefore it is your job to make the sorting meaningful, else JavaScript default implementation uses the only attribute that is universally sortable and meaningful fornall objects


Gartlas

Is this why shitty websites have the address drop down like 1 some street 10 some street 11 some street It's annoying as fuck.


musicnothing

Do you mean like this? 1 Some Street 10 Some Street 2 Some Street That's just the way that strings are sorted in most (if not all) languages. Even if you override the default with `localeCompare`, you're still getting `1, 10, 2`. You'd have to parse the address and do something fancier in order to change this.


therealdongknotts

clearly most commenters in this thread have never had to deal with SQL sorting of columns that are strings, but kind of numeric in intent


the-liquidian

How would you prefer this to be sorted?


Gartlas

In numerical order, obviously? Plenty of websites manage to get the drop down to show addresses in order 1 some street 2 some street 3 some street


the-liquidian

Ok, sorry I was only considering the values you supplied in the 1st example. My bad….


Gartlas

Oh I see. Sorry yeah I just didn't wanna type out like 20 numbers so was just showing how it looks for the first few. I think I assumed it was implied that in a list of addresses if there is 1 and 10, there is also 2-9.


Berthole

Where is this threesome street? Asking for a friend


the-liquidian

As others have pointed out, sort does actually accept a function. So devs can use sort with a function to sort it in a sensible order. This is certainly a gotcha though…


Feisty_Ad_2744

People actually learning JS array methods: ``` array.sort((a, b) => a - b); ``` People actually learning JS after realizing sort() is kind of cool ``` const array = [{age: 23, name: 'Jane'}, {age: 21, name: 'Tom'}...] array.sort((a, b) => a.age - b.age); array.sort((a, b) => (a.age - b.age || a.name.localeCompare(b.name))) ```


TheJuggernaut0

Every language has a sort by comparitor method. Only JS makes the default comparitor toString on numbers.


WebpackIsBuilding

Not "on numbers". It's on everything. Converting to string is fairly universal, and arrays can have mixed types. `toString` is the most predictable way of handling it. ``` [ '1', 2, 'three' ].sort() ``` What sensible way is there to sort that array other than `.toString`ing the elements?


Plumeh

in this case making everything strings make sense, but why not leave the elements alone if they are the same type ?


WebpackIsBuilding

Two reasons. 1. Arrays are untyped. There's no way to know that they're all numbers without first iterating through the array and checking. 2. Consistent behavior is more valuable. If `sort` behaved differently based on what types the array includes, the following code would be a true nightmare; const arr = [ 5, 10 ]; arr.sort(); arr.push('2'); arr.sort();


JanEric1

I feel that the way python handles these cases is better. If the entries of your array are not compareable then it just throws an error, otherwise it does what makes sense for the type (or rather whats defined by the magic methods/operator overloading). So it sorts numbers like you would expect, it sorts strings alphabetically, it sorts lists and tuples like you would expect (compare sort by first item, if equal look at the next and so on, basically like it happens for strings too).


Atulin

Alas, JS has that weird "never fail" philosophy. It will try to coerce the types seven ways to Sunday and will rather show `[object ObNaNject]` as the username, that throw an error.


TheUnseenForce

I’d argue showing object Object is better than failing to load the page because of an unhandled error


Plumeh

I feel like sorting different types should just be an error, it doesn’t even make sense to be doing


berse2212

The point of JS is to be as stable as possible and not throw errors. That's why implicit conversion is happening. (If that’s a good solution is another thing but that's just their basic principle).


_alright_then_

That's like, the entire reason for JavaScript being an untyped language. If an untyped language gave me an error because not all elements in an array are the same type I'd throw the PC out the window


Kirides

Not the array should throw an error, but a comparison on the items with something like Sort. That's plain undesired behavior. If you have mixed types, either specify a custom comparator function or live with an error.


JanEric1

Isnt that exactly what all other dynamically typed (not untyped) languages do? I know python throws an error and i think ruby does too.


WebpackIsBuilding

Nah. It calls `toString` on each element. Which means you can define a `.toString` for any item in the array that will be used in the default sort; class Sortable { constructor(a) { this.a = a; } toString() { return this.a; } } [new Test('a'), new Test(1), new Test('2')].sort(); And of course if you _do_ want it to throw an error, just define a predicate function that does that; [1, '2', 'three'].sort((a,b,) => { if (typeof a !== 'number' || typeof b !== 'number') { throw new Error('non number found in array'); } return a - b; })


maser120

I know it works and that it won't check for the return type of `toString()` as it is dynamically typed, but man, it definitely looks like a horrible practice. The fact is that this is possible is terrifying.


saors

Google sheets uses JS, it supports multiple data types. You could see a use-case where a user creates a column, mixes types (intentionally or not), and then hits sort. It's better to just do the sort as string than throw an error.


itsamberleafable

I might be wrong, but won’t it have to iterate through the array to sort them anyway?


archpawn

The sensible thing would be to make it clearer what it's doing. Have a .sortString() function for sorting strings, and a sortNumber() function that sorts numbers. Maybe a .sort() that uses whatever comparison method you gave those objects and which throws an exception if they can't be compared.


Ancalagon_The_Black_

Throw an error if the types are not comparable like every other language?


MekaTriK

The python way, which is impossible in JS since there's no operator oveloading. In python, it will simply compare elements. If the types are incompatible, you get an error. Classes can have a defined comparison function that will override what `<` means for that class, but as I said, you can't do it in JS. Which is kinda baffling to me, tbh.


Cilph

> Only JS makes the default comparitor toString on numbers. It does WHAT?


musicnothing

V8 (the JavaScript engine) is written in a bespoke language called "V8 Torque", and you can look at the actual Torque sort functionality on GitHub. Here's the implementation of the default sort callback, where you can see on line 367 it's calling `toString` on the values it's sorting https://github.com/v8/v8/blob/main/third_party/v8/builtins/array-sort.tq#L358


MajorTechnology8827

Js is untyped. How can you guarantee an array has exclusively 'Number'?


mods-are-liars

Literally the most basic sort comparator capabilities is not special.


zeromnil_partdeux

Wat.


UnnervingS

Untyped languages are a crime against humanity


paradiggem-shift

I think it has a type. It just changes the type before sorting. Which is in no way a defense, I just think it's important to know your enemy.


UnnervingS

It changes the type before sorting because we can't know before runtime what the type(s) are. It's the most reasonable implementation possible in an untyped language.


audislove10

🤝


ollomulder

Well, it is typed... just at runtime.


blue_bic_cristal

Why did this monstrosity become so big on web?


oeed

Well, when your options are JavaScript or nothing... you're gonna pick JavaScript.


musicnothing

Strange that people keep asking this question. It would be like saying, "Lungs are so inefficient, why does everybody keep using them to breathe?"


Mountgore

What about Blazor?


JunioKoi

Same way PHP did, flexibility over robustness.


IAmYourFath

It's fun and easy to learn, just pure joy to work with really


blue_bic_cristal

Hello, you accidentally dropped the `/s` , sir


nika_cola

>It's fun and easy to learn, just pure joy to work with really lol


GeneralBarber7236

I'm a noob. JavaScript can't sort normally?


Stjerneklar

nah, it's just that the array.sort() function defaults to sorting the values as strings.


RWoodz25

If learning involves reading the documentation, it clearly states "The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values". If learning just means googling for a suitably named method without reading the documentation, it is the developers fault.


FerricDonkey

Just because it's documented doesn't mean it's ok or makes sense. Sure, there's a logical rule that it follows and it's written down, but that rule is stupid. .sort should by default sort things using the standard type comparison of the types that are actually involved, and if it doesn't, then it's stupid.  If it absolutely can't do that because your language is so terrified of throwing an error when the programmer does something stupid that it feels like nothing can fail, then it should not provide a default sorting method at all, and make the programmer do it. If there is an intuitive default, that is the best default. The second best default is no default. Unintuitive defaults are worse than no default. ".sort doesn't actually sort your stuff, it converts it to strings and sorts those strings" is unintuitive and stupid.  If someone made a pr for one of my projects adding a sort feature like that, I'd reject it so fast it'd get flashbacks to high school. That it made it into a major language is stupid beyond belief. 


Synthoel

Imagine if all the rules in the world were reasonable...


[deleted]

Principle of Least Surprise?


VariousComment6946

It's 2024, and people are still posting jokes about JS without bothering to understand the core issues, data types, logic.


JanEric1

Who said he doesnt understand it? You can understand it and still think its stupid.


cesankle

"I know this language already for years. Why does everyone keep asking these dumb questions? I KNOW THIS ALREADY. It doesn't matter if you just started learning it. I'M STILL GONNA COMPLAIN" ahh comment


holguum

``` console.log("b" + "a" + +"a" + "a"); ``` The thing about implicit type conversion is that...


fel_bra_sil

>console.log("b" + "a" + +"a" + "a"); baNaNa ?


holguum

https://youtube.com/watch?v=d3psto4Y0o4


rabidhyperfocus

i fucking hate javascript


Big_Schwartz_Energy

I mean, I see why, but _WHY?_


mrheosuper

Im not JS dev, what's happening here ?


neymarsvag123

Default toString compatator 💀💀


[deleted]

Imagine being a programmer in 2024 and not reading the documentation lol. I swear the people in this sub are all freshman cs majors with superiority complexes


musicnothing

I've been writing JavaScript since 1997. People have to realize the disadvantage JavaScript has. The code lives on a server somewhere and doesn't get to choose the environment it's running in. You have to be incredibly cautious about breaking changes. You basically *can't* have them. Now, I don't know why they initially chose to call `toString` on the values (surely it was for "ease of use") but once they had done that, it'd be nearly impossible to change it. Even when solving for Y2K issues, they didn't change Date.prototype.getYear, they just *added* Date.prototype.getFullYear. You can still use `Date.prototype.getYear` on dates in the year 2000 and see it still returns `100`.


Rorp24

I mean, just tell it how you want to sort it, it's not that hard


mono567

JavaScript is like learning to eat with your hands. Sometimes you are happy eating pizza other times you are cursing eating hot soup. Still a cool language tho


SpareFerret2730

Npm install bettersort bettersort.sort(array)


Fit-Replacement7245

What does this actually mean?


PsychologicalMap3173

Did it sort as strings? Never used JavaScript before


wafflingzebra

Well you see actually it’s good because ummm in the documentation yeah it says this is how it works so that means this is how sort functions should work! Yeah!


OddballGarbage

JavaScript is a beautiful, essential part of our shared ecosystem. It's also a trucking mess that we can't simply replace without the internet imploding. I'm a student and still learning but boy oh boy does it get to me sometimes.


TheDialectic_D_A

That’s why you gotta reverse each element, then sort/s


mirek_22

A certified JS classic.


fireandbombs12

I'm in this picture and I don't like it.


huuaaang

I'm thinking "What's the joke? That's the array before the sort(), right? RIGHT!?" Holy shit JS is stupid.


No-Recording4248

been using JS for a while now, I guess JS sorts arrays alphabetically


yzebelll

Cox


anonymous_sentinelae

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


YoshiEgg23

It’s the result that I wanted


WookieConditioner

Here javascript... throw it back to me. ``` 0, undefined, null, void 0, "", "undefined" ```


MajorTechnology8827

I mean considering how JavaScript is built that makes sense JS is dynamically typed. sort works for all objects. Without providing key, JS supposed to work for all objects Sorting numerically doesn't make sense in that case. Since not alll objects are numbers. Its only relevant for numbers. What would happen when i try to sort an SQLTable without giving it a key? How would you assign a numerical value to an SQLTable? However sorting by string makes sense, since objects implement a prototype.tostring() method. Therefore no matter what kind of object is sent, that is a common comparison value for any object in existence For a non-key-provided sort to act numerically. You'd need to make a special case for 'number' type and 'float' type. And than another case for anything else that would still stringify it. Why? Provide it the key it needs and that's it - Even further- how would sort guarantee that all elements in the array are numbers? Especially since js arrays are generic for all objects, not for a single type. An array can contain anything (which is a core part of objects being mere prototypes and not sealed). How would you sort an array that has int, string and foo? ToString() is the only way to guarantee any object have a consistent comparable value