0

The code I found to sort a list of numbers by ascending order is:

arr.sort((a,b) => a-b);

I don't understand how the compare function works. What if you do arr.sort((a,b) => a+b)?

3
  • 1
    ..What if you do arr.sort((a,b) => a+b)?... Why don't you do that to see what happens? Commented Sep 10, 2020 at 19:27
  • 2
    It is very clearly explained in the documentation, try reading the function docs before posting a question. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 10, 2020 at 19:32
  • a more explicit version of that function would be (a,b) => { if (a < b) return -1; else if (a > b) return 1; else return 0; } Commented Sep 10, 2020 at 19:33

1 Answer 1

2

The sort function uses the sign of the value returned by the comparator:

  • Positive means A > B.
  • Negative means A < B.
  • Zero means A == B.

So a - b is just a neat shorthand which fulfills those cases.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.