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

104
Visualizações
Arrow function capture strategies for let declared variables

I've been reading Jon Skeet's article on closure capturing strategies and want to explore what's the case with JavaScript.

arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log(i));
}
arr.forEach(ele => ele());



arr = [];
let j;
for(j = 0; j < 3; j++) {
    arr.push(() => console.log(j));
}
arr.forEach(ele => ele());

Surprisingly, the first prints 0,1,2 and the second 3,3,3.

I also found that JS always captures variables. So why the first case?

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

0

arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log('1', i));
}
arr.forEach(ele => ele());



arr = [];
let k;
for(k = 0; k < 3; k++) {
    arr.push(() => console.log('2', k));
}
arr.forEach(ele => ele());

I've added the strings 1 and 2 inside the console.logs so that you can better see which one is actually going first.

The first to end is 1 and it works as expected because the let keyword is scoped to the for loop. On the other hand, console.log in the second loop takes k which is scoped in the window scope, thus when console.log runs, the value of k is going to be set to that of the end of the for loop, while the value of i is only valid and scoped (thus the closure) inside the first for loop.

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