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

442
Views
What's the difference between using a for loop with let and using a var?

I'm developing a small system but I noticed that there is a difference in using a loop for var and let, normally i always use let anyway but i decided to do some checks with var and that blew me away.

Example:
This works:

var inp = document.getElementsByTagName('input');
var focus = 0;
var inpLen = inp.length - 1;
inp[focus].focus();

for (let i = 0; i < inp.length; i++) {
    const e = inp[i];

    e.onkeyup = function () {
        if (e.value.length == e.max) {

            var leap = Math.min(i + 1, inpLen);
            inp[leap].focus();
        }
    } 
}
<input type="number" max="2">
<input type="number" max="3">
<input type="number" max="2">
<input type="number" max="3">

And it doesn't work:

var inp = document.getElementsByTagName('input');
var focus = 0;
var inpLen = inp.length - 1;
inp[focus].focus();

for (var i = 0; i < inp.length; i++) {
    var e = inp[i];

    e.onkeyup = function () {
        if (e.value.length == e.max) {

            var leap = Math.min(i + 1, inpLen);
            inp[leap].focus();
        }
    } 
}
<input type="number" max="2">
<input type="number" max="3">
<input type="number" max="2">
<input type="number" max="3">

My question is:
Why this happens, and how can I set my loop with var to work correctly

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!