You have to remember, under the hood of the javascript engine, sort
is simply a sorting algorithm. That algorithm can be any algorithm that accomplishes sorting. A browser could be using bubble sort (a terrible sorting algorithm generically speaking), or it could be using quick sort (more likely). In fact, if you look at similar questions, you'll find that browsers will use different sorting algorithms like quicksort or merge sort depending on the data type of the array to be sorted (e.g. Javascript Array.sort implementation?). At the heart of any sorting algorithm, from the most basic to the most complex, is a comparison between two items. In an iteration of the algorithm, the algorithm will decide, should item a
be sorted lower or higher than item b
(or the same)? That's it. The only real reason the algorithms get fairly complex is to optimize the efficiency of sorting. For example, on average, bubble sort will require on the order of n^2
operations to sort a list of n
elements, whereas merge and quick sort will require n*log(n)
(a much, much smaller number when n
is large) to sort a list of n
elements.
But all that doesn't really matter for all you care, you just want the list to be sorted in whichever way you want. In your case, you are saying that you want an item of a smaller length to be sorted in a lower position in the resulting list as compared to another string whose length is larger. That is all that your comparison function does - it is a generic way for the algorithm to know how to order items. I know the documentation is out there on this stuff, but I wanted to give you my take.
When you provide the comparison function to Array.sort
, then internally the algorithm will know that on every iteration (which compares two individual items), the algorithm will call your function on those two given items, and based on your function's output for those two particular elements, it will sort accordingly.