I hear what you're saying, but it still seems pretty bonkers to me that if you try to sort an array of numbers it will cast them to strings and sort alphabetically (!):
> [1, 2, 10, 3].sort()
[ 1, 10, 2, 3 ]
> And yes, I agree that throwing an error here for no argument would be better here (a linter WILL enforce this), but this is hardly a critical shortcoming of JS's standard library
I suppose "critical" is debatable but this seems very fundamental and very unexpected to me.
> you DEFINITELY do not need a utility library just to use the language (especially for your examples)
I hadn't actually considered using a linter to avoid these types of standard library footguns... that's actually a pretty great idea!
Since arrays can contain a mix of anything, I don't think it's that bonkers that the default impl chose to canonicalize values into consistent comparables with String(). It's just not useful for numbers.
But for example, they probably decided that it was more useful defaulting to having a sort order for things that otherwise aren't comparable:
Since null < undefined and undefined < null are both false, then a simple `a < b` comparator wouldn't sort them at all. Same for objects.
If you have an array that's a huge mix of random values, from null to undefined to [] to {} and you sort() it, all of those values will now be grouped together by type.
There would be a significant performance impact if `.sort()` argumentless had to traverse the list and checked all inputs were numbers. It's better to pass a sort function -- that is how the API is meant to be used.
I agree that without an argument it should just be a fatal error, but if it were to have any sort of functionality, it should convert all to strings.
This is consistent among JS's apis, and pretty much the origin of all the 'js wut' moments on the internet. Everything in JS can be converted into a string. If you do something stupid with disparate types, it will likely turn operands into strings and compare them that way.
I suppose "critical" is debatable but this seems very fundamental and very unexpected to me.
> you DEFINITELY do not need a utility library just to use the language (especially for your examples)
I hadn't actually considered using a linter to avoid these types of standard library footguns... that's actually a pretty great idea!