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

194
Vistas
In closures we know for each loop iteration variable "i" is a fresh copy, then why const "i" not work in a loop

/this code works and each callback is referencing to a different "i" it indicates that for each loop iteration a new copy of "i" is created, due to that the callback forms a closure with a distinct "i" each time/

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  setTimeout(function() {
  console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}

/This gives error: Assignment to constant variable. Why not in this case a new constant "i" is created for each loop iteration/

const arr = [10, 12, 15, 21];
for (const i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

++i doesn't modify the instance of i - it creates a new instance with an incremented value and assigns it back to i. If i is defined as a const, you cannot assign the value back to it, and hence the error.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Because a constant must not be changed, you can't i++ on a constant.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

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