Tutorial / JavaScript

Keep the right index when you listen for clicks

Beginner1 min6 Dec 2026

You have a row of buttons and you want each click to report its own position. A for loop that uses var, or a single let declared outside the loop and reused carelessly, often logs the same final number for every button.

The version that stays correct

forEach passes a fresh index into each callback. The arrow function closes over that binding, so the first button keeps 0 and the second keeps 1.

JavaScript
const buttons = document.querySelectorAll("button");

buttons.forEach((button, index) => {
  button.addEventListener("click", () => {
    console.log(index);
  });
});

The version that collapses

var is function-scoped. Every handler created in this loop reads the same i after the loop has finished, so each click prints the length of the list.

JavaScript
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", function () {
    console.log(i);
  });
}

What to remember

  • Prefer forEach or for...of when the body only needs the current item.
  • If you stay with a counted loop, declare the index with let so each iteration gets its own binding.
  • When the handler is added later, log the value at the moment you attach it if you are unsure what it closed over.

Related