the sort array method is the hardest one I have ever faced I watched a lot of tutorials and did read about it the condition in the callback functions seems really hard to understand I do not want to copy solutions I want to understand it
here where I am stuck JavaScript’s default sorting method is by string Unicode point value, which may return unexpected results.
what unexpected values mean I used the sort method on an array of numbers before and it worked how could that be an unexpected result?
ok this is a clear example where it is a minus operation
but how could it return less than 0 when the compare function comparing the a and b using the comparison operators it should return true or false
The callback function, for each pair of values it’s given, should return less than zero for the one that should come before the other, zero if they’re the same, or greater than zero for one that should come after the other. Not true or false.
So
return a - b
Can also be written as
if (a < b) {
return -1;
} else if (a === b) {
return 0;
} else if (a > b) {
return 1;
}
It will do the same thing (note: for the array of numbers used in your example)
If the callback function returns the difference of two numbers of the array to be negative, then it knows that the first one is smaller than the second, which means they are already in a sorted order and nothing needs to be done. A 0 difference means both are same. And if the difference is positive then the two numbers definitely need to be sorted because the first is greater than the second.