If you just had this code:
var values = [ 213, 16, 2058, 54, 10, 1965, 57, 9 ];
values.sort();
Then the values would be sorted using a default comparison function. You would end up with them sorted alphabetically with each value in the array treated as a string.
When you pass a function as a parameter to the sort function then it will sort according to that function. For any two values it will swap them according to whether the return value is a positive or negative value. Specifically (according to MDN):
- If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
- If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
- If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
- compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
Using a difference function is convenient if and only if you can guarantee that all values are numbers and that the difference never overflows. The provided comparison function will sort the array in descending order.