-5

Here, it gives me the output of 0, 1, 2 just like the for loop except it only logs one number at a time.

I'm new to jQuery and I just stumbled across this line of code here. Can anyone explain the mechanic behind the working of this code? The thing that left me baffled is the third line of code.

var i = 0;
setInterval(() => {
  i = (i + 1) % 3;
  console.log(i);
}, 1000);
Ghoul Fool
  • 4,667
  • 9
  • 54
  • 100
KruzeZab
  • 5
  • 1

1 Answers1

0

i = (i + 1) % 3; does two things

  1. Increase i by 1
  2. Use the modulo operator with argument 3 , This will result in every integer i to yield the values 0, 1, or 2, depenting on the remainder of the integer division (
    1 % 3 = 1,
    2 % 3 = 2,
    3 % 3 = 0,
    4 % 3 = 1,
    5 % 3 = 2,
    6 % 3 = 0,
    etc.)

You could rewrite it to i++; i %= 3, if you wish to make these two steps more obvious. But this will not be necessary, as I assume any programmer will instantly understand the original line of code.

yunzen
  • 30,001
  • 10
  • 64
  • 93