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

This is a repeat. No incrementer in x + 2. It should be 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 += 2;

Why:
In JavaScript, the expression ‘x + 2’ calculates a new value but does not modify ‘x’ itself. To update ‘x’, the result of the addition must be assigned back to ‘x’, either with ‘x = x + 2’ or the shorthand ‘x += 2’.


Got it: @kirupa :trophy:

First-answer leaderboard

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

Yeah this is a classic. seen it cause more than a few headaches with junior devs on my team.