title: Understanding javascript closure with event handlers
body: <p>I'm very new to javascript, recently while understanding closures I came across one question asked by Interviewer:-</p>
  
  <pre><code>function initButtons() {
      var body = document.body,
          button, i;
  
      for (i = 0; i &lt; 5; i++) {
          button = document.createElement("button");
          button.innerHTML = "Button " + i;
          button.addEventListener("click", function (e) {
              alert(i);
          }, false);
          body.appendChild(button);
      }
  }
  initButtons();
  </code></pre>
  
  <p>What will be output of this code? For which I replied - "Number corresponding to button.. 1, 2 etc."</p>
  
  <p>Okay, then I googled around and found a answer, which stated:-</p>
  
  <blockquote>
    <p>The reason this happens is because when the addEventListener method is
    invoked during each iteration of the for loop a closure is created.</p>
  </blockquote>
  
  <p>Okay, now everything is going above my head... How is this possible? To be frank enough, I'm a dumb in javascript and trying to learn as much possible. So, I am going thru the basics!!</p>
  
  <p>In the mean while I am also reading details of <a href="https://stackoverflow.com/questions/111102/how-do-javascript-closures-work/5099447#5099447">how-do-javascript-closures-work</a></p>