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

230
Vistas
Troubles understanding the use of let in a loop context

This is not a programming problem, it is just a question about a topic with scopes in JavaScript that I would like to understand better.

The following code loops through a serie of class elements and click on them at random interval rates between 250 and 750 ms. A very basic code but the curious (and most difficult thing to understand to me is the use of the let declaration for the i variable in the for loop.

var x2 = document.querySelectorAll(".someClass");
for (let i=0; i < 35; i++){
    setTimeout(function(){
        x2[i].click();
    }, i*(Math.random()*(750-250) + 250));
}

Without the let, that is, if I would have used var instaad of let (and this either in the loop declaration, outside the loop or globally) the x[2] element would be undefined. If I create a new scope inside the loop, this code would not work as expected. Instead of clicking the x2[i] element with a random delay 35 times, it would first wait the random delay and then click all the elements at once.

But, as far as I know, the let declaration only means that the i variable would have a scope limited for the for loop. Why would using var make it undefined? And, if I wrap the call in another anonymous function to create a scope, which is counter-intuitive, the result would be a completely buggy behaviour. How all this is possible? Is that a design flag in JavaScript or is this a common fact in many other programming languages?

Am I missing anything?

about 4 years ago · Juan Pablo Isaza
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