Sort array alphabetically with a callback function

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;

In the function above, can someone please explain the part :
return a === b ? 0 : a < b ? 1 : -1;
What exactly is happening here?

I believe the positive and negative value indicates the index being greater or less than in relation to the item being compared. I’m sure someone else on here can give a more thorough and even correct explanation…

Hopefully this resource can assist…

This section in particular:

If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, “banana” comes before “cherry”. In a numeric sort, 9 comes before 80, but because numbers are converted to strings, “80” comes before “9” in the Unicode order. All undefined elements are sorted to the end of the array.

If compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction ). If a and b are two elements being compared, then:

  • 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).
    ** compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.

What @randomTask says is correct. The documentation he provides is the interesting one, but those explanations can sometimes be a bit confusin. Let’s see if I can help a bit!

The sort function expects a function with two input arguments (which will be members of the sorted array) and a return value that can take 3 types of values: 0, greater than 0 (in the example they chose 1) and lower than 0 (in the example they chose 0).
If the callback method given to sort returns

  • 0: a and b have the same priority, so no need to change their position in the array
  • 1: a should come after b in the array (the index of a will be greater than that of b)
  • -1: a should come before b (the index of a will be lower than that of b)

Hope this help! :slight_smile: