-1

I wonder why in this code counter is not saving after it is incremented? I mean now the behavior is the same as if I used if (counter+1 % 2). But ++ operator supposed to permanently increment the variable.

let counter=0;
for (let i = 0; i < 10; i++) {
    console.log(counter,'every')
    if (counter++ % 2) console.log(counter,'odd');
}
ogbofjnr
  • 1,688
  • 5
  • 19
  • 41

2 Answers2

3

I believe you want to have ++ in front of counter

let counter=0;
for (let i = 0; i < 10; i++) {
    console.log(counter,'every')
    if (++counter % 2) console.log(counter,'odd');
}
depperm
  • 10,606
  • 4
  • 43
  • 67
  • 1
    See also: [Arithmetic operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Examples_7) – esqew Jul 11 '19 at 16:51
-1

If you use the ++ operator after the variable it will only increment after the line code is executed, if you put it behind the variable it will increment before the line code.