Search code examples
javascriptloopsinfinite-loop

i++ loops without any problem, i+2 loops infinitely and crashes


I want to create a simple loop function that adds 2 every time it loops. However, even though I tell my for loop to stop if the number reaches or is less than 100, it goes past 100 and loops infinitely.

i++ works just fine:

function addTwo() {
  for (i = 0; i <= 100; i++) {
    console.log(i);
  }
}

addTwo();

When I change it to i+2 it crashes:

function addTwo() {
  for (i = 0; i <= 100; i + 2) {
    console.log(i);
  }
}

addTwo();

I expect the console to log: 0 2 4 6 8 ... 100.

But instead it loops infinitely and crashes.


Solution

  • i+2 in your case does nothing. JS evaluates it and then does nothing with the calculated value, this means that i is never increased.

    ++ is a special operator that increments the variable preceding it by 1.

    To make the loop work you have to assign the value of the calculation i+2 to the variable i.

    for (i=0; i<=100; i = i+2) {
        console.log(i);
    }
    

    or

    for (i=0; i<=100; i += 2) {
        console.log(i);
    }