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

180
Visualizações
Difference between var and let in for loop

for(var i = 0; i < 5; i++){
  setTimeout(() => console.log(i)
}

    for(let i = 0; i < 5; i++){
      setTimeout(() => console.log(i)
    }

Why the loop with let return 0,1,2,3,4 but loop with var return 5,5,5,5,5 ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is because of hoisting. Declaring a variable with var in your for loop doesn’t limit its scope to just that block of code like it would using let. Since its existence extends beyond that for loop, when the value is evaluated by the setTimeout() callback, you get the last value it was set to. (it gets set to 5, which is why the for loop stops)

for (var val = 0; val < 5; val++) {
  setTimeout(() => console.log(i)
}
if (val === 5) {
  console.log('I can still see the value');
}

You can see the same behavior while using let if you’ve already declared the variable before using it in your for loop.

let i;
for (i = 0; i < 5; i++) {
  setTimeout(() => console.log(i)
}

Now it would behave the same way as the var for loop did.

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