Spot the bug - #155: Scoreboard Sorter

Sorting bug hiding in here.

const scores = [12, 4, 30, 21];
scores.sort((a, b) => a > b);

console.log(scores);

Reply with what is broken and how you would fix it.

The sort comparator needs to return a negative, zero, or positive number to indicate order, not a boolean. a > b just gives you true or false, which JavaScript then tries to turn into 1 or 0. That’s not enough for a proper sort.

You’d fix it for ascending order with scores.sort((a, b) => a - b);.

Spot the Bug answer: The comparison function for sort is incorrect, leading to an improperly sorted array.

The fix:

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

Why:
The default sort behavior in JavaScript converts elements to strings and sorts them lexicographically. A custom comparison function should return a negative value if ‘a’ comes before ‘b’, a positive value if ‘a’ comes after ‘b’, and zero if they are equal. The provided function ‘a > b’ returns true (which is coerced to 1) or false (coerced to 0), which does not consistently provide the necessary negative, zero, or positive values for a correct numeric sort.

First-answer leaderboard

  1. @kirupa - 8 (firsts) :trophy:
  2. @emmawalter5 - 7 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)