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

231
Visualizações
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 à 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