Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

497
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda