For this, I would recommend you take a look at the MDN or the devdocs.io page for the sort function. But here’s the gist.

Array.sort() takes a function, which it will use for sorting comparison. That function should return one of two values: a positive number or a negative number. If a negative value is returned, the first item will get a lower index value (will come first). If zero, they are equal by the comparison, and will remain unsorted. If greater than 0, then the second item being compared will get a lower index (will come first).

So, in the function

function(a, b){
return a-b;
}

we’re assuming that we’re sorting a numeric list. If our list was [5, 2, 3, 8, 1], then the sort function would sort them based on that criteria. First, it would take 5 and 2, and return 5-2; (or return 3). As that is a positive value, the second (the 2) would be assigned a lower index.

That is grossly oversimplified, but that is the theory. There is a complex interaction between the various members of the array, far more than just “compare the zero-th index to the first index, then compare the first to the second, then…” But all we need to know is, when any pair of values are compared, they will be compared using the function we have specified.

That actually makes a lot of sense. I always understood (and used) .sort() alone without any functions. I thought it automatically sorted them from least to greatest without needing any additional parameters.