0

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?

3
  • 4
    Because - doesn't behave like >...? Commented Dec 24, 2020 at 1:22
  • What's the sence for the comparing? Commented Dec 24, 2020 at 1:25
  • Then where should be use - and > ??? Is there any specific datatype ?? Commented Dec 24, 2020 at 1:27

1 Answer 1

1

sort compare method does the following possible comparisons for both cases. This explains the discrepancy in output

enter image description here

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);

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.