Understanding callback function in sort method

Working on this challenge:

This is my code:

function alphabeticalOrder(arr) {

  // Only change code below this line

return arr.sort(function(a, b) {

  return a === b ? 0 : a < b ? -1 : 1;

});

  // Only change code above this line

}

alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);

Which works and is all fine. But I don’t understand how it works.

How does this :

return a === b ? 0 : a < b ? -1 : 1;

tell the machine what to do?

Same question for the sort method applied to numbers. How does this code tell the machine how to sort them in ascending order?

return arr.sort(function(a, b) {
    return a - b;

I read it a “minus” b. Is that what is going on? If so, how does that help the machine sort the numbers in ascending order?

Thanks to anyone who will help me understand

the sort method takes a callback and sort the array elements based on the callback:

if the callback returns 0 for two elements then it doesn’t change the relative order of the two elements

if it returns -1 (or a negative number) then it will put a before b

if it returns 1 (or a positive number) it will put b before a


it works the same if instead of 1 or -1 it returns any positive or negative number
a - b is negative if a is smaller, so it means that a will have to go before b
a - b is positive if a is bigger, so a will go after b

1 Like

thank you @ilenia that is much more clear now

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.