Spot the bug - #93: 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 comparator is returning a boolean (a > b), but Array. prototype. sort expects the compare function to return a negative number, zero, or a positive number. With a boolean you end up with inconsistent ordering because true gets coerced to 1 and false to 0, and you never return a negative value. Fix it by returning a numeric difference:

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

Kirupa has a decent explainer on why this matters:

Https://www.

kirupa. com/html5/sorting_arrays_js. htm