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

254
Visualizações
Unable to figure out the output of simple javascript code

function func2() {
  for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

Due to closure, the console.log statement should remember its outer lexical environment, which is first setTimeout and then the for loop. Since i is not available in the setTimeout context, it looks in the execution context of the for loop, and searches for the value of i there.

Now, that value, after 2 seconds, should have been 3 for all three executions of console.log. But it displays the output as:

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

0

You have used let which is block scoped so there will be separate i for each for loop iteration.

1) If you want to output consective 3 so you can declare i outside of for-loop, then there will be only single i with the value 3.

function func2() {
  let i;
  for (i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

2) If you want same lexical scope then you can also use var here,

var is function scoped, So there will only be one i

function func2() {
  for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

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