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 beforeb
. -
if it returns
0
, the ordering ofa
andb
won’t change. -
if it returns a positive value,
b
will be ordered beforea
.
Now, let's understand how the comparison function sort(a, b) => a - b
sorts in ascending order:
-
If
a - b
is negative, it means thata
is less thanb
, soa
should come beforeb
in the sorted order. -
If
a - b
is positive, it means thata
is greater thanb
, soa
should come afterb
in the sorted order. -
If
a - b
is zero, it means thata
andb
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.