Why does this javascript code output the same result?
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
I'd expect to see in 1, 2, 3, 4. It feels like it's something related to lexical scoping, but what's the real reason behind?
Can someone explain exactly how this piece of code work behind the scenes?