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

233
Visualizações
Why do you need to use const in this JavaScript for loop?

I have some HTML buttons. One labeled "Next", one labeled "Back". Each should call their respective function on click.

HTML

    <div class="buttons">
        <button class="lastQuestion">Back</button>
        <button class="nextQuestion">Next</button>
    </div>

JS

function nextQuestion() // not including full code inside function
function lastQuestion() // not including full code inside function

I am iterating over the buttons and listening for clicks. I am calling the function depending on their text content. This only works when I specifiy const for each iteration. If I don't, both buttons call nextQuestion(). I haven't tried this with let, but I would like to know why this is the case in JavaScript? I'm new to JS specifically.

This works:

for (const btn of navButtons) {
    btn.addEventListener('click', () => {
        if (btn.textContent === 'Next') {
            nextQuestion();
        } else {
            lastQuestion();
        }
    })
}

This does not:

for (btn of navButtons) {
    btn.addEventListener('click', () => {
        if (btn.textContent === 'Next') {
            nextQuestion();
        } else {
            lastQuestion();
        }
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

const it is block scoped variable. So engine creates new one for every iteration.

And second case doesn't work because btn created as global variable and every iteration just re-assign it. So in this case you always have only one variable with latest assigned value.

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