title: How scope works in a for loop?
body: <p>When I created 5 buttons in a loop and click the value of i is always 6 </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function createButtons() {
     for (var i = 1; i &lt;= 5; i++) {
       var body = document.getElementsByTagName("BODY")[0];
       var button = document.createElement("BUTTON");
       button.innerHTML = 'Button ' + i;
       (function(num) {
         button.onclick = function() {
            alert('This is button ' + num);
         }
       })(i);
       body.appendChild(button);
     }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>but when I change the scope of i to block scope(using IIFE or let keyword) it gives the right value of i. How does it working under the hood of javascript?</p>