-1

Given the following function:

    let ticks = 0;
    let clock = setInterval(() => {
      console.log("tick", ticks++);
      if (ticks == 10) {
        clearInterval(clock);
        console.log("stop.");
      }
    }, 200);

Why is the first thing logged to the console "tick 0" rather than "tick 1", since it is immediately incrementing ticks by 1 (ticks++)? Or, is it the case that JS sees "ticks" first and immediately logs that, then sees the ++ and increments it accordingly?

JMP
  • 4,417
  • 17
  • 30
  • 41
CSG
  • 67
  • 8

1 Answers1

1

ticks++ evaluates to ticks, and after that, adds 1. You probably want ++ticks.

It jumps at you right at the start of the documentation of the ++ operator:

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description

connexo
  • 53,704
  • 14
  • 91
  • 128