title: Javascript infamous Loop issue?
body: <p>I've got the following code snippet.</p>
  <pre><code>function addLinks () {
      for (var i=0, link; i&lt;5; i++) {
          link = document.createElement(&quot;a&quot;);
          link.innerHTML = &quot;Link &quot; + i;
          link.onclick = function () {
              alert(i);
          };
          document.body.appendChild(link);
      }
  }
  </code></pre>
  <p>The above code is for generating 5 links and binding each link with an alert event to show the current link id. But It doesn't work. When you click the generated links they all say &quot;link 5&quot;.</p>
  <p>But the following code snippet works as our expectation.</p>
  <pre><code>function addLinks () {
      for (var i=0, link; i&lt;5; i++) {
          link = document.createElement(&quot;a&quot;);
          link.innerHTML = &quot;Link &quot; + i;
          link.onclick = function (num) {
              return function () {
                  alert(num);
              };
          }(i);
          document.body.appendChild(link);
      }
  }
  </code></pre>
  <p>The above 2 snippets are quoted from <a href="http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/" rel="nofollow noreferrer" title="here">here</a>. As the author's explanation seems the <strong>closure</strong> makes the magic.</p>
  <p>But how it works and How <strong>closure</strong> makes it work are all beyond my understanding. Why the first one doesn't work while the second one works? Can anyone give a detailed explanation about the magic?</p>