Interesting behaviours behind Javascript's sort() method

Javascript Sort() Behaviours

Something I learned today that I find interesting is how the sort() method in Javascript selects its sorting method at runtime. I was playing around on pythontutor.com while practicing the "is it an anagram?" leetcode challenge on Scrimba and noticed something odd.

When you sort the string "convexsphere" is compares index 0 with index 11.

Initial comparison

However, if I sort the string "rosie" (my cat) it compares index 0 with index 1 first ... huh?

Second comparison

Apparently the sort sequence is chosen by the Javascript engine under the hood. In this example the sort method decided what characters to sort first based on the length of the array.

HOWEVER, this isn't accurate as of July 2026, because I checked what node version pythontutor.com was running and it returned v.6.0.0, which uses an older sorting alg that assesses sort order based on character length. In v6, smaller arrays used to default to an insertion sort, whereas longer arrays defaulted to quick-sort.

None of this matters anymore because the most up-to-date JS engine uses something called Timsort, which scans the array to find small segments that are already sorted, and then a bunch of other more efficient oprerations.

TimSort begins by examining the first two elements of the array, but after that I'm not entirely sure what it would do to the previous two examples.

Anyways. Fascinating stuff. I mainly wanted to look this up because I was curious what the values of a, and b were in the callback method. So, in case you ever wanted to know, the a and b in your callback are simply whichever two elements the engine has decided to compare at that moment.