Closures inside loops and local variables
<p>I am a JS novice and I was reading about closures, the common issues that arise due to misunderstanding how closures work and the "setting handlers inside a loop" was a pretty good example. I've also seen and understood the ways to get around this, i.e, by calling another function passing the loop variables as arguments and returning a function. Then I tried to take a dip to see if there are any other ways to get around this and I created the following code.</p>

<pre><code>var i;

var inpArr = new Array();

for(i = 0; i &lt; 10; ++i) {
  inpArr.push(document.createElement("input"));
  inpArr[i].setAttribute("value", i);
  inpArr[i].onclick = function() {
    var index = i;
    alert("You clicked " + index);
  }
  document.body.appendChild(inpArr[i]);
}
</code></pre>

<p>It doesn't work which I guessed but I don't understand why. I understand <code>i</code> was captured and made available to all the function expressions generated. But why does this still not work after assigning the captured variable to the local variable <code>index</code>? Isn't assigning <code>i</code> the same as passing <code>i</code> as an argument to another function? I mean, isn't <code>i</code> a primitive and isn't it supposed to be copied?</p>

<p>I am confused and I would really appreciate it if someone could tell me what's going on here.</p>