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.
var i;
var inpArr = new Array();
for(i = 0; i < 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]);
}
It doesn't work which I guessed but I don't understand why. I understand i
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 index
? Isn't assigning i
the same as passing i
as an argument to another function? I mean, isn't i
a primitive and isn't it supposed to be copied?
I am confused and I would really appreciate it if someone could tell me what's going on here.