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

86
Visualizações
why infinite loop doesn't apply when iterating backwards with for loop

I am learning javascript and I have two questions hope you can help :)
I have two for loops iterating backwards

  • first example :
for (var i = 10; i--;) {
  console.log(i, "backward");
}
// starts at 9 and stops at 0
// without breaking condition
  • second example :
for (var i = 10; i >= 0; i--) {
  console.log(i, "backward");
}
// starts at 10 and stops at 0
// with breaking condition that i >= 0
  1. why in the first example we don't need to set a breaking point for the loop ? like i > 0 ? is it because 0 is false anyway ? so when it reaches 0 it automatically breaks ? and it won't keep iterating like 0, -1, -2, -3, ....etc ?
  2. why in the second example the iterating starts at 10 while in the first example it starts at 9 ?

thanks for your support :D Cheers

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  1. i-- is the breaking point. A post-decrement expression subtracts 1 from the variable and returns the previous value. So when i is 0, the value of i-- is 0, which is falsey, and the loop stops.
  2. Because in the first example we're decrementing i during the repeat condition, which runs before the body, so the first iteration already has it decremented to 9. In the second example we're decrementing i in the update expression, which runs after the body, so it still has the initial value 10 during the body of the first iteration.

To understand what a for loop is doing, expand it into the analogous while loop.

for(initialize; condition; update) {
    body
}

is roughly equivalent to

initialize;
while (condition) {
    body;
    update;
}
almost 4 years ago · Santiago Trujillo 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