Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

495
Views
Why does this for loop keep incrementing when the condition is false?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!