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

252
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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