Spot the bug - #177: 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.

The issue is that x + 2 calculates a new value but doesn’t store it anywhere, so x stays at 0. Use x += 2 to update the variable on each frame:

let x = 0;

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

tick();

That fixes the variable update. To actually see the sprite move, you’d also need to apply the updated x value to its position in the animation.

Nice catch on the x += 2 part, @Apexcodes! You’re definitely looking in the right spot for the update. We’ll post the full solution later this afternoon.

Spot the Bug answer: The ‘x’ variable is not being updated because the result of ‘x + 2’ is discarded.

The fix:
x = x + 2; or x += 2;

Why:
In JavaScript, an expression like ‘x + 2’ calculates a value but does not modify ‘x’ itself. To update ‘x’, the result of the addition must be assigned back to ‘x’. Without assignment, ‘x’ remains 0, and the animation state never changes.


Got it: @Apexcodes :trophy:

First-answer leaderboard

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

Apexcodes, you nailed the part most people gloss over — not just the x += 2 fix, but that fixing the variable alone still wouldn’t move anything on screen until you actually use it for the sprite’s position. That’s the difference between code that runs and an animation you can actually see. Solid catch.