Reputation: 17
var arr = [undefined,null, NaN , Infinity];
sample.sort((a,b)=> a-b)
Answer : [Infinity, NaN, null, undefined]
sample.sort((a,b)=> a>b ? 1 : -1)
Answer : [null, NaN, Infinity, undefined]
Can anyone explain why there is a difference between the sort function?
Upvotes: 0
Views: 53
Reputation: 11001
sort compare method does the following possible comparisons for both cases. This explains the discrepancy in output
const output = [];
[Infinity, NaN, null, undefined].forEach((a, i, arr) =>
arr.forEach((b) => output.push({
a,
b,
"a - b": a - b,
"a>b ? 1 : -1": (a>b ? 1 : -1)
}))
);
console.log(output)
console.table(output);
Upvotes: 1