Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!