Maybe this will help someone:
Compare function takes two parameters, which are named “a” and “b”.
const compare = (a, b) => {}
If the function’s returned value is a negative number (ex. -1), then the first argument (in this case “a”) will be sorted before the “b” argument (ie. at an index lower then “b”).
If returned value is a positive number (ex. 1), then the first argument (“a”) will be sorted after the “b” argument (ie. at an index higher then “b”).
If function block contains statement:
return a - b;
and for example, the value of “a” is 100 and the value of “b” is 200, then a - b expression returns a value of -100, which is a negative number and the “a” argument will be sorted before the “b” argument.
If you reverse the values, “a” is 200 and “b” is 100, then a - b expression returns 100, which is a positive number and the “a” argument will be sorted after the “b” argument.
The sorting outcomes of both examples may be different, but the smaller number was always sorted before the bigger number. So that means an expression a - b will always put the smaller number before the bigger number (array will be sorted in ascending order).
Statement :
return b - a
will always sort the array in descending order. If value of “a” is 100 and value of “b” is 200, result is 100 and “a” is sorted after “b” (ie. in descending order) and vice versa.
You could achieve ascending sorting with either of the if statements:
if (a < b) {
return -1;
}
// or
if (a > b) {
return 1;
}
Both examples will sort the smaller number before the bigger number.