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

231
Views
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 answers
Answer question

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 Report
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!