0

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?

Startec
  • 12,496
  • 23
  • 93
  • 160

2 Answers2

3

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;
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Right. So, if the the initial value is incremented and then overwritten, wouldn't it be overwritten to `1` then '2' etc? – Startec Apr 09 '15 at 20:06
  • 1
    ahh, I see. Your link cleared it up - the old value is always returned so it is continually overwritten. – Startec Apr 09 '15 at 20:12
1

when working with pre- and postfix operators, it's often good to write down the code which is actually executed.

i ++

means:

tmp1 = i
i = i + 1

(tmp1 is the result of the whole operation). while

++ i

means

i = i + 1
tmp1 = i

That means

i = i ++ % 3

is actually

tmp1 = i
i = i + 1
i = tmp1 % 3

As you can see, the second line as never an effect because the last line overwrites it.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • A little lost on your second and and fourth examples here. is `tmp1 = i` wrong here because it assigns the value of `i` to `tmp1` (not a reference?) – Startec Apr 09 '15 at 20:10
  • A number is a value type, i.e. it never changes its value. `i=1` means: Create an instance of type number and put `1` into it and assign the reference to the alias `i`. So `tmp1 = i` copies the reference and `i = i + 1` creates a new instance with the value `i + 1` and assigns this again to `i`. That way, the value of `tmp1` doesn't change. – Aaron Digulla Apr 09 '15 at 20:26