Blessed Are the JavaScript Developers
I know this seems weird at first glance, but JS arrays are not typed. To all the people saying this is obviously wrong, I&#x27;m curious what your intuitive default strategy is to sort the following array:<p><pre><code>  [
     7,
     &#x27;3&#x27;,

     {},
     null,
     undefined,
     NaN,
     Infinity,
     new Date(),
     new Error(),
     Promise.resolve(),
     function () { return &#x27;a&#x27;; },

     { toString: ()=&gt;&#x27;a&#x27; },
     { toString: ()=&gt;7 },
     { valueOf: ()=&gt;&#x27;b&#x27; },
     { valueOf: ()=&gt;9 },
     { __proto__: Number.prototype, 
       valueOf: ()=&gt;&#x27;a&#x27;, 
       toString: ()=&gt;7 },
  ].sort()
</code></pre>
The big thing everyone is always complaining about with Javascript is that it tries to guess too much. Type conversions with equality operators, type conversions with +&#x2F;- operators, lots of Javascript doing unexpected conversions and trying to be helpful at the wrong times.<p>So sure, you <i>could</i> have a set of random rules based on prototype chains to figure out whether you were going to call `valueOf` or `toString` for any given object, and you could come up with a bunch of rules for whether or not primitive types like Symbols come before numbers.<p>Or, you could just say, &quot;we&#x27;re going to convert every value to its string representation and sort alphabetically.&quot; At which point, as long as you understand how string conversion works, it becomes very obvious and easy to understand how the array above will get sorted.<p>The second option is easier to learn and easier to reason about. There&#x27;s weird stuff in Javascript, but if you&#x27;re going to have a default (and there&#x27;s good reason to say that you shouldn&#x27;t, and that `sort` without a parameter should just throw an error), I think this is the <i>right</i> choice for them to have made about how the default should work.<p>Lots of intuitions about what the developer meant seem simple when you&#x27;re only looking at the simple case. But it is usually better to have one set of rules that are easy to describe and that are universally applied. More of Javascript should work this way, if we&#x27;re going to have a default sorting algorithm, then it&#x27;s good that the default sorting algorithm mostly does the same stuff every time no matter what you pass it.<p>This is not the kind of thing that makes me dislike Javascript, it&#x27;s the other stuff -- the inconsistencies and magic behaviors -- that give me more pause about the language. But what Javascript is doing here is good.