Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?

The sort callback has to return

  • a negative number if a < b
  • 0 if a === b
  • a positive number if a > b

Three possible return values are needed because the sort function needs to know whether a is smaller than, equal to, or larger than b in order to correctly position a in the result array.

It is very common to just return -1, 0 and 1 if you working with non-numerical data (I guess that's why W3Schools mentions it). But if you use numerical data, you can simply subtract the values because

  • if a < b then a - b < 0, i.e. a negative number
  • if a === b then a - b === 0, i.e. 0
  • if a > b then a - b > 0, i.e. a positive number

W3Schools is not very precise which is one of the reason why you should avoid it. Use MDN instead.


It is not bound to be -1, 0, 1 any negative or positive number will do the trick.

But how it works? The sort() method needs to know the relation between each two elements in order to sort them. For each pair (according to the algorithm used) it calls the function then based on the return value, may swap them. Note that a-b returns a negative value if b>a and a positive one if a>b. That leads to an ascending order.

Just for test, replace a-b with b-a and you will get a descending order. You may even make it more complicated, sort them based on (for example) their least significant digit:

a.sort(function() {return (a%10) - (b%10);}

If Function(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.

If Function(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 behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

If Function(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first. Function(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.

Tags:

Javascript