0

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();
        }
    })
}
madmonkey
  • 83
  • 8
  • How did you get the `navButtons` – TropicsCold Jan 10 '22 at 06:22
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of – HDM91 Jan 10 '22 at 06:24
  • On each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. – HDM91 Jan 10 '22 at 06:24
  • 1
    `for (btn of navButtons)` creates a *global* variable called `btn` which all of the event listeners use, therefore `btn.textContent` is going to be exactly the same for each event listener as opposed to using a different value for `btn`. – VLAZ Jan 10 '22 at 06:29

1 Answers1

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.