Menu

1 / 2

JavaScript .sort(), "Why b - a, Not a - b"

DEV Community·Mohamed Idris·6 months ago
#rAN7lakf
#sorting#javascript#beginners#sort#shifts
Reading 0:00
15s threshold

The thing that always trips people up

You see this in someone's code:

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

Enter fullscreen mode

Exit fullscreen mode

And you think:

"Why subtract?"

"Why b - a and not a - b ?"

"What does this even return?"

Three minutes from now you will never forget it.

How .sort() actually works

Array.sort() reorders an array. To do that, it needs to compare two items at a time and decide which one goes first. You teach it how by giving it a compare function .

The contract is one rule:

compareFn(a, b) returns: a NEGATIVE number → a comes first a POSITIVE number → b comes first ZERO → leave them in their current order

Enter fullscreen mode

Exit fullscreen mode

That is it. The function returns a number; the sign is the only thing that matters.

The cute mental model

Think of the compare function as a referee judging a match between two contestants, a and b . After the match, the referee gives a score.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.