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

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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