Spot the bug - #115: Moving Sprite Position

Find the bug in this animation loop.

let x = 0;
function tick() {
  x + 2;
  requestAnimationFrame(tick);
}
tick();

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

You’re missing the assignment operator there. x + 2; calculates the value but doesn’t actually update x. It should be x = x + 2; or x += 2; .

Spot the Bug answer: The ‘x’ variable is not being updated because the result of the addition is not assigned back to it.

The fix:
x = x + 2;

Why:
In JavaScript, ‘x + 2;’ calculates a value but does not store it. To update ‘x’, the result of the addition must be assigned back to ‘x’ using an assignment operator like ‘=’ or ‘+=’, otherwise ‘x’ will always remain 0.

First-answer leaderboard

  1. @kirupa - 4 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)