var myAlerts = [];
for (var i = 0; i < 5; i++) {
myAlerts.push(
function inner() {
alert(i);
}
);
}
myAlerts[0](); // 5
myAlerts[1](); // 5
myAlerts[2](); // 5
myAlerts[3](); // 5
myAlerts[4](); // 5
why the all the values at positions 0-4 in array are "5". I found some article regarding this as Javascript supports Lexical scoping rather than Dynamic. Yes, I got that. But is there any way to understand this core concept for the above snippet Thank you
In this particular functionality value
i
is dynamic and it will be replaced with new value whenever you make change in value of i.i is getting considered as value by reference.
So if you you change it to for loop till 10 you will have all i's replaced with 10.