I included the console.log to try to follow along what is happening (which didn’t really help). I think I understand that this is a method that include existing calculations (and switching of the numbers in the array?) that I’m not seeing here. (i.e. I don’t need to understand everything I’m seeing here? Because it’s certainly not self-explanatory!) But what confuses me is, why doesn’t the ascSort function return the a - b equation? For example, shouldn’t it return -20 the first time through the method?
If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).
“with” is a bit incorrect in this context. sort() function requires compareFunc to do the sorting. In the case when you’re using it without arguments it just uses internal compareFunc.
@snigo So compareFunction is somehow “operating” but not being called? Isn’t it being called within the sort() function? Or can a function “operate” as an argument but not get called?
That’s my point. To me, return a - b; would be the same as saying return 25 - 5 and the return value should be 20. (and then it seems like 20 should be added to the array). Then 200 - 5 etc. Yes the code says return a - b but it doesn’t seem like the code is returning the subtraction of 25 - 5.
the sort method takes a function as argument, and it uses that function to compare the values and sort the array. the sort method uses the return value from the callback to sort the array. Then it returns the array.
You don’t see the function passed to sort being called, so also you don’t see its output
Ok thank you. And the comparison to determine whether or not 20 is greater than 0 occurs in the compareFunction? Basically I’m not seeing what the compareFunction is doing here, right? And the compareFunction isn’t being called but it is being used?
The compare function is the function that returns a number. Depending on whether or not that number is greater than zero, the sort function will arrange the array.