title: Using var in for loops and using closures give different results
body: <p>I wrote this code:</p>
  <pre><code>&lt;html&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;script&gt;
          var btn = document.getElementsByTagName(&quot;button&quot;);
          for(var i = 0; i&lt;5; i++){
            btn[i].onclick = function(){alert(i)}
          }
        
      &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>
  <p>and for every click, I get the same result that refers to the last <code>i</code> value</p>
  <p>Then i tried to wrapp it with clousre, and its worked fine:</p>
  <pre><code>&lt;html&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;button&gt;Click&lt;/button&gt;
      &lt;script&gt;
          var btn = document.getElementsByTagName(&quot;button&quot;);
          for(var i = 0; i&lt;5; i++){
            btn[i].onclick = createAlert(i)
          }
          
          function createAlert(i){
              return function(){
                  alert(i)
              }
          }
  
      &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>
  <p>Can someone explain to me what is going on behind the scenes and why it's working fine?</p>