Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

496
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda