You can see it like this. When you have two numbers, compare a (previous) and b (next).
If a is greater than b, put it after b.
If a is less than b, put it before b.
In fact, when you have the case "a> b", you can return any positive number: put a after b.
And, when you have the case of 'a <b', you can return any negative number: put a to b. This is essentially a comparison of two numbers at a time.
The position in the array can be understood below. Seen from the perspective of return ab , if you are returning a negative number, put a to b; if you return a positive number, put a after b. negative numbers are zero positive numbers.
Perhaps you can understand this better by printing the content to n at runtime.
window.n = [4, 11, 2, 10, 3, 1]; n.sort(function(a, b) { console.log(a); console.log(b); console.log(window.n); // You can see what is in n in the every comparison console.log('--') return ab; });
Result in Chrome v64.0.3282
4 11 (6) [4, 11, 2, 10, 3, 1] -- 11 2 (6) [4, 11, 2, 10, 3, 1] -- 4 2 (6) [4, 11, 11, 10, 3, 1] -- 11 10 (6) [2, 4, 11, 10, 3, 1] -- 4 10 (6) [2, 4, 11, 11, 3, 1] -- 11 3 (6) [2, 4, 10, 11, 3, 1] -- 10 3 (6) [2, 4, 10, 11, 11, 1] -- 4 3 (6) [2, 4, 10, 10, 11, 1] -- 2 3 (6) [2, 4, 4, 10, 11, 1] -- 11 1 (6) [2, 3, 4, 10, 11, 1] -- 10 1 (6) [2, 3, 4, 10, 11, 11] -- 4 1 (6) [2, 3, 4, 10, 10, 11] -- 3 1 (6) [2, 3, 4, 4, 10, 11] -- 2 1 (6) [2, 3, 3, 4, 10, 11] -- (6) [1, 2, 3, 4, 10, 11]
Your code returns the same result as below:
var n = [4, 11, 2, 10, 3, 1]; n.sort(function(a, b) { console.log(a); console.log(b); console.log('--') if (a > b) { return 1; } else { return -1; } }); (6) [1, 2, 3, 4, 10, 11]
OR
var n = [4, 11, 2, 10, 3, 1]; n.sort((a, b) => a > b ? 1 : -1); (6) [1, 2, 3, 4, 10, 11]