What's the scope of a Javascript variable declared in a for() loop?

Posted by Dylan Beattie on Stack Overflow See other posts from Stack Overflow or by Dylan Beattie
Published on 2010-04-28T21:57:14Z Indexed on 2010/04/28 22:07 UTC
Read the original article Hit count: 331

Check out the following snippet of HTML/Javascript code:

<html>
<head>
<script type="text/javascript">
var alerts = [];
for(var i = 0; i < 3; i++) {
    alerts.push(function() { document.write(i + ', '); });
}

for (var j = 0; j < 3; j++) {
    (alerts[j])();
}

for (var i = 0; i < 3; i++) {
    (alerts[i])();
}
</script>
</head><body></body></html>

This outputs:

3, 3, 3, 0, 1, 2

which isn't what I was expecting - I was expecting the output 0, 1, 2, 0, 1, 2,

I (incorrectly) assumed that the anonymous function being pushed into the array would behave as a closure, capturing the value of i that's assigned when the function is created - but it actually appears that i is behaving as a global variable.

Can anyone explain what's happening to the scope of i in this code example, and why the anonymous function isn't capturing its value?

© Stack Overflow or respective owner

Related posts about puzzle

Related posts about JavaScript