Need an explanation. why we are returning a-b?

var sorting = ages.sort(function(a,b){
    return a-b;
})
console.log(sorting);

Good question!

sort is a fairly general method that compares elements of the array in some way and uses the comparison to put the elements in order

The function we supply gives a value that’s less than 0 if a is less than b, 0 if a is equal to b, and greater than 0 if b is less than a. That’s the way the sort function knows which way around to put these elements.


You might then think why do I have to supply a function? shouldn’t the function we’ve put there be the default??

Which is an excellent thought to have! One reason is that we want the sorting default function to be as general as possible so it works on a wide range of things. A somewhat natural choice in JS is to coerce things into strings and compare the strings.

This means that unfortunately, numbers get compared incorrectly unless we pass in the simple function like we have done here.

3 Likes