var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]
simply change that to
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){console.log("comparing " + a + ", " + b);return a - b}) //Array now becomes [7, 8, 25, 41]
after you try the above code in the console log you will see the following result
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){console.log("comparing " + a + ", " + b);return a - b}) //Array now becomes [7, 8, 25, 41]
is interpreted to be ascending? It's supposed to be divided into three cases, <0 , ==0, and >0 ; but how does this make sense when a and b can be anything?
FIRST COMPARISON : 25,8
Now, lets answer your doubt of how it choses the value of a, b. When you run the code you see the first comparison is made between 25,8 and if result is positive then it means that 8 is smaller. So it simply re-orders it to 8, 25.
SECOND COMPARISON : 25,7
Next comparison is made between 25 , 7 and that is because if the result is negative then the third number will be put after 25 and the sorting of the three numbers would be done.
But the case is different, now as the result again comes a positive. The array yet re-orders itself to
8, 7, 25
after that it again performs the test until it finds that the condition is positive. So now it compares 8, 7 and the result is again negative.
The array again re-orders itself to
7, 8, 25
THIRD COMPARISON : 25, 41
Now, in this last comparison, the result comes as positive, which means that 41 is greater than 25.
hence the array reorders itself to
7,8,25,41