Home > Net >  Why does this for loop keep incrementing when the condition is false?
Why does this for loop keep incrementing when the condition is false?

Time:06-16

I have the following loop:

for (let i = 100; i > 1; i  ) {
    console.log(i);
    i = 1;
}

When i enters the for loop again it is 1 so the condition i > 1 is false but it keeps looping infinitely and printing 2.

I also tried with i !== 1 and/or i but the same thing happens.

Same behaviour in other languages:

for (int i = 100; i > 1; i  ) {
    std::cout << i << std::endl;
    i = 1;
}

Output:

...
2
2
2
...

As far as I know the increment operation should not happen if the condition is false.

CodePudding user response:

The syntax of a for loop is:

for ([initialization]; [condition]; [final-expression])
   statement

(quotting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for), the final-expression is:

"An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable."

Your statement block ends with setting i to 1. Before entering the next iteration, the loop's final-expression is performing the increment, thus setting i to 2 before repeating the statement block.

CodePudding user response:

So what I understand from Dave's answer is that what happens inside the for loop is:

for (let i = 100; i > 1;) {
    console.log(i);
    i = 1;
    i  ;
}

and not:

for (let i = 100; i > 1;) {
    i  ;
    console.log(i);
    i = 1;
}
  • Related