How does Array.sort((a, b) => a - b) in JavaScript work?

The sort method takes a compare function as an argument, and this function is used to determine the sorting order of the elements.

It takes two parameters (a and b) that represent any two elements from the array, and its return value determines how they should be sorted:

  • if it returns a negative value, a will be ordered before b.

  • if it returns 0, the ordering of a and b won’t change.

  • if it returns a positive value, b will be ordered before a.

Now, let's understand how the comparison function sort(a, b) => a - b sorts in ascending order:

  • If a - b is negative, it means that a is less than b, so a should come before b in the sorted order.

  • If a - b is positive, it means that a is greater than b, so a should come after b in the sorted order.

  • If a - b is zero, it means that a and b are equal in terms of sorting, and their relative order doesn't matter.

Therefore, using sort(a, b) => a - b method results in sorting the array in ascending order.

If you wanted to sort in descending order, i.e. bigger numbers first, you’d need your function to return b - a to invert the logic.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda