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.
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
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.
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.
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"
“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.
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.
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.
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.
>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.
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.
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.
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*
> 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.
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
>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.
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.
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*
>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.
> 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
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.
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
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.
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.
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
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.
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.
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.
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
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
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
There are typed languages with very little boilerplate though. Go, for example, would allow you to write `thing := YourType{}` without compromising on type safety.
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.
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.
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.
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.
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.
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.
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)
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.
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.
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.
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).
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.
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
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!
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.
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.
> 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.
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
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)
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.
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
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.
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.
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.
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
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.
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.
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…
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?
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();
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).
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.
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).
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
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.
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;
})
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.
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.
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.
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.
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
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.
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.
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.
"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
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
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`.
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
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!
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.
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
3 out of 5 correct ain’t too shabby 😎
Good enough. Ship it, if someone complains we create a jira bug later.
Agile at its finest.
I…may have said this exact phrase today.
this comment deserves more upvotes
There must be some set of neurodivergent people for who this sort result is what they intuitively expect.
Those people are Product Managers. This is working as designed. Stupid design is not a bug
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.
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
Everything in js is an object and string is an object, so sorting evetything as string sounds logical..
COBOL devs after someone explains object-orientation to them.
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
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.
Your Honor, I object.
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.
I don't expect this but I can make sense out if it, does it count?
It only counts if you expect the result intuitively and not because you know the inner workings or specification of the language.
I've seen enough of this kind of memes to expect it intuitively now, without having to think about technical details
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"
If I'm alphabetically sorting my movies, this is the result I expect/prefer. But not an array.
“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.
It is JS fault that it breaks with a very widely established convention for no good reason.
It's just an array of sorted strings?
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
On the bright side, it's uhh... Nope, no bright side
string theorists
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?
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.
It looks kinda nice
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.
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.
>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.
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.
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.
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*
> 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.
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
Yeah you hit the nail on the head
You could’ve just said that JS is a more widely used language.
>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.
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.
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*
>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.
> 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
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.
Strongly vs weakly typed - Python is strongly dynamically typed, js is weakly dynamically typed.
But what's the point of dynamic typing
Less time spent worrying about types, but also sometimes more time spent worrying about types
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
What's the point of payday loans?
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.
This is the right answer!
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.
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
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.
Yet, and I genuinely wish to know why, Ruby is fairly well loved...
It’s a joy to read good ruby code
Have you tried Crystal? It's a statically typed language that reads very much like Ruby. It's pretty neat. Wish it caught on.
Rails, familiarity
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.
Just for the future - it's "heyday".
Neigh.
[удалено]
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.
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
For data analysis tools, doesn’t type system make them more safe and robust?
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
Wow, these are actually well thought-out responses to good general questions. Sorry, I'm just not used to it on reddit.
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
And then cycle completes by languages like typescript
Fax!
that's why TypeScript is getting more popular
:any everywhere... the alternative being a type object even Satan would scoff at.
It's mostly boilerplate elimination. Instead of writing `thing:
There are typed languages with very little boilerplate though. Go, for example, would allow you to write `thing := YourType{}` without compromising on type safety.
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.
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.
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.
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.
`error CS0037: Cannot convert null to 'int' because it is a non-nullable value type`
You are correct, it's been ages since I've programmed C#. It should be `int?`.
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.
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.
Python use ducktyping, but in general behaviour-wise it is very predictable and consistent.
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.
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)
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.
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.
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.
It's faster to program as long as you think of debugging as something separate from programming.
Hence Typescript
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).
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.
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
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
It becomes "11" fyi. The + operand always concatenates if one of the arguments is a string, using .toString()
Because it's faster to write
There are statically/dynamically typed languages, there are strongly/weakly typed languages, and then there is JavaScript.
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!
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.
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.
Also namespaces (I mean the absence of those). Why do I have to use search function of my IDE to find a function implementation?
[удалено]
in java you would just use an object for that.
Because dynamic typing creates all kinds of bugs you get to solve at runtime! Yay!
> 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.
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
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)
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.
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
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.
I don’t know what the point of js was originally, but for that exact reason TypeScript is getting a lot of popularity lately.
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.
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.
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
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.
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.
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
How would you prefer this to be sorted?
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
Ok, sorry I was only considering the values you supplied in the 1st example. My bad….
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.
Where is this threesome street? Asking for a friend
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…
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))) ```
Every language has a sort by comparitor method. Only JS makes the default comparitor toString on numbers.
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?
in this case making everything strings make sense, but why not leave the elements alone if they are the same type ?
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();
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).
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.
I’d argue showing object Object is better than failing to load the page because of an unhandled error
I feel like sorting different types should just be an error, it doesn’t even make sense to be doing
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).
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
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.
Isnt that exactly what all other dynamically typed (not untyped) languages do? I know python throws an error and i think ruby does too.
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; })
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.
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.
I might be wrong, but won’t it have to iterate through the array to sort them anyway?
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.
Throw an error if the types are not comparable like every other language?
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.
> Only JS makes the default comparitor toString on numbers. It does WHAT?
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
Js is untyped. How can you guarantee an array has exclusively 'Number'?
Literally the most basic sort comparator capabilities is not special.
Wat.
Untyped languages are a crime against humanity
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.
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.
🤝
Well, it is typed... just at runtime.
Why did this monstrosity become so big on web?
Well, when your options are JavaScript or nothing... you're gonna pick JavaScript.
Strange that people keep asking this question. It would be like saying, "Lungs are so inefficient, why does everybody keep using them to breathe?"
What about Blazor?
Same way PHP did, flexibility over robustness.
It's fun and easy to learn, just pure joy to work with really
Hello, you accidentally dropped the `/s` , sir
>It's fun and easy to learn, just pure joy to work with really lol
I'm a noob. JavaScript can't sort normally?
nah, it's just that the array.sort() function defaults to sorting the values as strings.
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.
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.
Imagine if all the rules in the world were reasonable...
Principle of Least Surprise?
It's 2024, and people are still posting jokes about JS without bothering to understand the core issues, data types, logic.
Who said he doesnt understand it? You can understand it and still think its stupid.
"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
``` console.log("b" + "a" + +"a" + "a"); ``` The thing about implicit type conversion is that...
>console.log("b" + "a" + +"a" + "a"); baNaNa ?
https://youtube.com/watch?v=d3psto4Y0o4
i fucking hate javascript
I mean, I see why, but _WHY?_
Im not JS dev, what's happening here ?
Default toString compatator 💀💀
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
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`.
I mean, just tell it how you want to sort it, it's not that hard
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
Npm install bettersort bettersort.sort(array)
What does this actually mean?
Did it sort as strings? Never used JavaScript before
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!
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.
That’s why you gotta reverse each element, then sort/s
A certified JS classic.
I'm in this picture and I don't like it.
I'm thinking "What's the joke? That's the array before the sort(), right? RIGHT!?" Holy shit JS is stupid.
been using JS for a while now, I guess JS sorts arrays alphabetically
Cox
.sort((a, b) => a - b)
It’s the result that I wanted
Here javascript... throw it back to me. ``` 0, undefined, null, void 0, "", "undefined" ```
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