You can see it this way. When you have two numbers, compare the a (the previous one) and b (the next one).
If a is bigger than b, put it after b.
If a is smaller 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 'a < b', you can return any negative number: put a before b.
It is essentially comparing 2 numbers at a time.
The position in the array can be understood as below.
Looking from the perspective of return a-b
, if you return a negative number, put a before b; if you return a positive number, put a after b.
negative numbers - zero - positive numbers.
Perhaps, you can understand it better by printing out content in n during 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 a-b;
});
Result on 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] // result
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] // result
OR
var n = [4, 11, 2, 10, 3, 1];
n.sort((a, b) => a > b ? 1 : -1);
(6) [1, 2, 3, 4, 10, 11] // result