Sorting out the sort() Method

Javascript sort() is one of four handy methods to loop through arrays. The others are map(), filter(), and reduce(), but we’ll stick to sort() for now. Of course, you can read up on it at, but I find this doesn’t adequately give you a full understanding of how it works.

Within that article, “some ordering criterion” is mentioned. But what are they talking about? What “ordering criterion”? Sure it works, but I’ve never been satisfied with these black box explanations. If you happen to be one who is, then stop reading now.

Let’s consider a simple descending numerical array that we want to convert into an ascending one.

sort an ascending array

Pretty straightforward. But hang on. The sort() method also accepts an optional parameter in the form of a function. This can be quite useful in cases where, say, you want to alphabetically sort a list of songs but want to ignore any articles such as ‘The’ that the title may contain. A little more coding would be required, but I will stick to the simple numbered array example to illustrate further. The following code will do the exact same thing.

alternate sort method

What are a & b? Why does it return a 1 and -1? Where does it return them to? ?

All right, so as if by magic, our array is converted from descending to ascending, but how? What’s the algorithm? The fact is, every browser has its own methods for interpreting and displaying HTML on the screen. So it shouldn’t be surprising that they also have their own unique sorting algorithms. Hmm, so how does Javascript handle this?

In short, Javascript doesn’t care what algorithm each browser uses. The sort() method provides only enough information for whatever algorithm is being used. Let’s get back to my confused friend’s questions and then we will compare Chrome to Firefox.

The values a & b are any two elements within the array. I use the word ‘any’ intentionally because sort() will loop through the array and compare these two values. In doing so, there will only be 3 possible outcomes: 1. a > b, 2. a < b, and 3. a = b. Depending on the criteria you use, case 1 may return the value 1 and case 2 return the value -1. Case 3 will obviously do nothing.

The magnitude of the returned numbers is not important, only whether they are positive or negative. You can use ‘return +27’ and ‘return -14’ and it will still work. But return that value to where? It is delivered back to the sort() method because it needs that information to determine if the order of the two compared values are to be changed or not.

Let’s now have a look at how two different browsers handle their respective sorting algorithms. The numbers in red are the a & b values that the algorithm will compare. You will notice that in Chrome, the values simply switch their positions, whereas in Firefox, a single value is moved in front of the one it is being compared to.