Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?
javascript
Solution
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.
Problem
My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed work, but my question is why?! I would really like to understand this piece of code properly. The site, W3 Schools says: You can fix this by providing a function that returns -1, 0, or 1: ``` var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a,b){return a-b}); ``` Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want. Again, if this is an incredibly dumb question I apologise.