title: How do these JS code snippets work?
body: <p>I'm reading about closures, and I had difficulty understanding the difference between these 2 code snippets:</p>
  
  <pre><code>var myElements = [ /* DOM Collection */ ];
  
  for (var i = 0; i &lt; 100; ++i) {
      myElements[i].onclick = function() {
          alert( 'You clicked on: ' + i );
      };
  }
  </code></pre>
  
  <p>The above code should only display <code>i</code> as 99 for every onclick</p>
  
  <pre><code>function getHandler(n) {
      return function() {
          alert( 'You clicked on: ' + n );
      };
  }
  
  for (var i = 0; i &lt; 100; ++i) {
      myElements[i].onclick = getHandler(i);
  }
  </code></pre>
  
  <p>And this code above displays the correct value of 'i' for every element click event!</p>
  
  <p>I can't understand why the 1st one doesn't display the correct value of <code>i</code>. And if not, why does the 2nd one display the correct value??</p>
  
  <p>They were taken from <a href="http://james.padolsey.com/javascript/closures-in-javascript/" rel="nofollow">this link</a></p>