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

443
Vistas
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
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