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

182
Visualizações
With setTimeOut, why it console 4, 5 times ? javascript

If I run this code then it console 4 at 5 time, can anyone explain why it is happening ?

let number = 1;

for (var i=0; i<5; i++){
  number=i;
  setTimeout(()=>{
    console.log(number)
  },1000)
}

Also if I modify this to as below then output is 5 times 5 ?

for (var i=0; i<5; i++){
  setTimeout(()=>{
    console.log(i)
   },1000)
 }

And why it prints 0 to 4 when we use let like

    for (let i=0; i<5; i++){
  setTimeout(()=>{
    console.log(i)
   },1000)
 }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Its a typical use case of var being functional scope ,every iteration of for loop shares the same value of var (doesn't creates a new scope as var being functional scope) which is kind of global in here

so when the last condition arrives i<5 i is already has become 4 ,and it is shared by every callback of setTimeout so they all prints 4 ,4 times

But in case of let a new scope is formed in every iteration ,as let being a block scope (for loop has a block scope)

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