I am trying the sort() method with a comapreFunction and I do not understand how the compareNumbers() works. Used with the two variables it returns -3, but when used on an array with the sort method it returns a sorted array. Why does it work like this?
var things = ['Elvis',555,'R2D2'];
function compareNumbers(a, b){
return a-b;
}
var a = 5;
var b = 8;
console.log(compareNumbers(a,b)); //returns -3
console.log(compareNumbers(things));//returns NaN
console.log(things.sort(compareNumbers(a,b)));//returns a sorted array
What is the logic behind the sort method used with the compareFunction so that it returns a sorted array? Why doesn't it return NaN?
Where can I check what is the code behind a method like library or documentation?
I saw this Understanding sort() compareFunction but it is just overwhelming for me at this stage.