I have code on JavaScript.
var a = [];
for (var i = 0; i < 5; i++) {
a[i] = function () {
alert(i);
};
}
a[2]();
If I invoke a[2]() I expect to see a message with 2 but instead of this I see 5.
To fix it I can rewrite it like this:
for (var i = 0; i < 5; i++) {
(function (v) {
a[i] = function () {
alert(v);
}
})(i)
}
But I cannot understand how does it work. So why I need to wrap my function code to closure?