Spot the bug - #144: Arcade High Score

Why is my high score leaderboard sorting 100 below 20?

const rawScores = [45, 12, 100, 8, 230, 95, 5];

function formatLeaderboard(scores) {
  const sorted = [...scores].sort();
  
  return sorted.reverse().map((score, rank) => {
    const badge = rank === 0 ? "👑" : "⭐";
    return `${badge} #${rank + 1}: ${score} pts`;
  });
}

function renderLeaderboard(scores) {
  const entries = formatLeaderboard(scores);
  const listContainer = document.querySelector("#arcade-board");
  
  listContainer.innerHTML = entries
    .map(entry => `<li>${entry}</li>`)
    .join("");
}

renderLeaderboard(rawScores);

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

Spot the Bug answer: The Array.prototype.sort() method, when called without a compare function, sorts elements as strings.

The fix:

Change .sort() to .sort((a, b) => a - b).

Why:
By default, JavaScript’s sort method converts elements to strings and compares them based on their Unicode code point values. This causes ‘100’ to be considered ‘less than’ ‘20’ because ‘1’ comes before ‘2’. Providing a compare function (a - b) ensures numerical sorting.

First-answer leaderboard

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

Oh man, this one gets everyone at some point. It’s like when you’re lining up kids by age but some of them have names that start with ‘A’ and ‘B’ and you accidentally sort by name instead of their birth year.

The issue is .sort() treats numbers as strings, so 100 can appear before 20.

Fix it with numeric sorting:

const sorted = [...scores].sort((a, b) => b - a);

Then remove .reverse().

This sorts scores correctly from highest to lowest.

ah, a classic! thanks for taking a look, @emmawalter5. we’ll post the full solution later today.

You’re right! The default sort() method converts numbers to strings for comparison.

Using (a, b) => b - a in the sort function is the correct way to get a numeric sort from highest to lowest.