Kevin Powell - CommunityKP-C
Kevin Powell - Community2mo ago
18 replies
Faker

How can a temporary variable be "saved" inside an event handler

Hello, quick question, consider the following code:

<h3>Click these buttons (Created with 'let'):</h3>
<div id="let-container"></div>


const container = document.getElementById('let-container');

    for (let i = 1; i <= 3; i++) {

      const btn = document.createElement('button');
      btn.innerText = `Button ${i}`;
      btn.addEventListener('click', () => {
        console.log(`You clicked the button that was created when 'i' was: ${i}`);
      });
      
      container.appendChild(btn);
    }


My question is, when we add the event listener for each instance of the button, even though i is normally a temporary variable, it's value gets stored and can be referenced when we actually click on the button, can someone explain why pls.
Was this page helpful?