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

137
Views
var keyword inside for loop statement explanation

I trying to understand some concepts of java script. I wrote this code:

<html>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <script>
        var btn = document.getElementsByTagName("button");
        for(var i = 0; i<5; i++){
         btn[i].onclick = function(){alert(i)}
        }
    </script>
</html>

for each click on each button I will get the same result "5", if I would change the var to let, I will get the correct result. can someone explain why it happened?

about 4 years ago · Juan Pablo Isaza
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!