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

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

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 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