Sorting numbers: Help to explain the code please

Can someone please explain to me, what’s going on with function(a, b){return a-b});

const numbers = [10, 7, 9, 5, 6, 3, 1, 8];

function arrange() {
 return numbers.sort(**function(a, b){return a-b}**);
};

console.log(arrange());

Cheers!

By default sort() function sort values as string.However, if numbers are sorted as strings "35" is bigger than "100", because 3 is bigger than 1.
And because of this, sort() will produce incorrect result when sorting numbers.
But it can fix by providing a compare function to the sort().
the purpose of compare function is to define an alternative sort order.
if you have compare function for sort() as follows :

const numbers = [10, 7, 9, 5, 6, 3, 1, 8];
numbers.sort(function(a, b){return a-b})

If compare function returns negative value then a is sorted before b.
Else if compare function returns positive value then b is sorted before a.
Else compare function returns 0 then no changes are done with the sort order of the two values.

1 Like