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

157
Vistas
Using var in JavaScript with a for loop issue?

I know I can use the let keyword here to get the desired outcome, but I would like to know why clicking on the div items alerts #5 for each div.

var div;
var box = document.getElementById('box');
for (var i = 0; i < 5; i++) {
  div = document.createElement('div');
  div.onClick = function() {
    alert('this is box # ' + i);
  }
  box.appendChild(div);
}
<div id="box"></div>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you assign the anonymous function to the click, it does not run its body. Its body of codes runs only when it is clicked so the first time i variable is used in the function it has already the value of 4. You need to evaluate current value of i while it is in the loop and place it in the function generated, by a function generating function. Otherwise it will take a reference to i and use its latest value always.

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