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,
awill be ordered beforeb. -
if it returns
0, the ordering ofaandbwon’t change. -
if it returns a positive value,
bwill be ordered beforea.
Now, let's understand how the comparison function sort(a, b) => a - b sorts in ascending order:
-
If
a - bis negative, it means thatais less thanb, soashould come beforebin the sorted order. -
If
a - bis positive, it means thatais greater thanb, soashould come afterbin the sorted order. -
If
a - bis zero, it means thataandbare 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.