title: Scope with a self-invoking function in Javascript
body: <p>Take below code iterates over 6 input buttons and attaches an <code>onclick</code> event to every button that alerts the index number of the respective iteration:</p>
  
  <pre><code>for (var i = 1; i &lt; 6; ++i) {
      var but = document.getElementById('b_' + i);
      (function (el) {
          var num = i;
          but.onclick = function () {
              alert(num);
          };
      })(but);
  }
  </code></pre>
  
  <p>As you can see, in each iteration there is a self-invoking function that creates a scope to store the iteration index in that scope.</p>
  
  <p>I have always used this type of pattern to attach an event that is dependant on a variable that is changed during iterations.</p>
  
  <hr>
  
  <p>Can anyone explain to me exactly why the above works, and how the <code>num</code> variable is captured in the scope?</p>
  
  <p>Also, is the self-invoking function used above called a <code>closure</code> ?</p>