I am trying to make a function that increments until it reaches 3 and then starts back from zero (so, called three times it would log 0
then 1
then 2
. When using the %
operator with the pre and post fix operators, I have confusing results.
Here are my two functions:
var i, j = 0, 0
function run () {
console.log(i);
i = i++ % 3;
} // Called three times logs 0, 0, 0
And
function newRun () {
console.log(j);
j = ++j % 3;
} // Called three times it logs 0, 1, 2
Why does the prefix operator work and the postfix does not (i.e. in the first function why is i
never incremented?
This doesn't have anything to do with the modulo operator. Even
i = i++;
doesn't work - it takes a value, increments it, and then overwrites it with the initially taken value. See also Difference between i++ and ++i in a loop? for how they work.
You probably want to write
i = (i + 1) % 3;