Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

446
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda