#18 · Shared references

Find the bug · #18 · Shared references Hard JavaScript

The players list gets sorted by score

After the “Top players” card loads, the main players list is suddenly sorted by score.

On this page

The report

Bug report

The players page lists everyone in the order they joined. Once the “Top players” card has loaded, the main list is suddenly sorted by score instead.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// The three highest scores, for the "Top players" card.
function topThree(players) {
  return players.sort((a, b) => b.score - a.score).slice(0, 3);
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
const players = [
  { name: 'Asha', score: 40 },
  { name: 'Ravi', score: 90 },
  { name: 'Meera', score: 70 },
  { name: 'Kabir', score: 10 },
];
console.log(topThree(players).map((p) => p.name).join(', '));
console.log(players.map((p) => p.name).join(', '));

It prints

Ravi, Meera, Asha
Ravi, Meera, Asha, Kabir

It should print

Ravi, Meera, Asha
Asha, Ravi, Meera, Kabir
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 calls players.sort(...). Array sort sorts in place and returns the same array, so working out the top three reorders the caller’s list as a side effect. Sort a copy: [...players].sort(...), or use toSorted.

The fix

1// The three highest scores, for the "Top players" card.2function topThree(players) {3  return players.sort((a, b) => b.score - a.score).slice(0, 3);3  return [...players].sort((a, b) => b.score - a.score).slice(0, 3);4}

How you’d find it

  1. Reproduce: call topThree, then print the original list. It’s sorted by score.
  2. The function was supposed to only read the list, so look for anything that changes it. slice makes a copy; sort doesn’t.
  3. Check the docs or try it: a.sort() === a is true. Same array, now reordered.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

const players = [{ name: 'A', score: 1 }, { name: 'B', score: 3 }, { name: 'C', score: 2 }];
const top = topThree(players);
assert.deepEqual(top.map((p) => p.name), ['B', 'C', 'A']);
assert.deepEqual(players.map((p) => p.name), ['A', 'B', 'C']);

Where else this bites

  • React: sorting props or state in place causes bugs that are hard to trace.
  • Python’s list.sort() versus sorted(list); Java’s Collections.sort versus sorting a copy.
Your progress stays on this device.