The sort() function is a little odd.
I’m assuming that it does a bubble sort - it iterates through the array and if one element is larger than the previous, it swaps them. It keeps looping through the array until no changes are made - i.e., the array is sorted. (I’m guessing that it’s a bubble sort - it could be something else - the result is the same.)
The “problem” with doing numbers is that sort assumes that you are doing strings, so it thinks that “142” is “lower” than “9”. Useful if you’re alphabetizing strings, but not for numbers.
That is what sort() assumes. By providing a function, you are overriding it’s comparison function and giving it a new one. You are saying “The standard sort() comparison techniques doesn’t work for me, so I’m providing my own.” When it evaluates that function, it compares the current element (a) with the next element (b). If the function returns a positive number, then sort() swaps the values. If it returns a 0 or a negative number then those two elements are in the right order so it leaves them alone. It keeps looping though the values until no changes are made.
Would it make more sense if we wrote it like this?
array.sort(function(currentValue, nextValue) {
if (nextValue > currentValue) {
return 1; // swap these values
} else {
return -1; // leave alone (could return 0, no diff)
}
});
The if could return any positive number and the else could return 0 or any negative number - it doesn’t change how sort() will respond - positive numbers mean that they are out of the order that you are defining, negatives mean that they are in the order that you are defining. (You could have a much more complicated function, like if you wanted a complicated sort order for objects, based on the relationships of multiple values in those objects.)
Writing it the below way accomplishes the same exact thing:
array.sort(function(a,b){
return b - a;
});
Yes, it’s weird. I’m not new to programming but am new to JS so this was a weird thing for me too, but it does makes sense once you dig into it.