Skip to content

Instantly share code, notes, and snippets.

@itod
Last active October 6, 2015 20:38
Show Gist options
  • Save itod/3050315 to your computer and use it in GitHub Desktop.
Save itod/3050315 to your computer and use it in GitHub Desktop.
JavaScript Closure
function foo() {
var res = [];
for (var i = 0; i < 3; i++) {
res.push(function() {
document.write(i);
});
}
return res;
}
var funcs = foo();
for (var i = 0; i < funcs.length; i++) {
funcs[i]();
}
// prints:
// 333
@anoiaque
Copy link

anoiaque commented Jul 5, 2012

I don't have clear explanation. Just, that 'var i' in for loop is bind to foo() and i in function(){...document.write(i)} is evaluated at the last value of i of the for loop.

By removing var in for loop it works as expected
... for (i = 0; i < 3; i++) { ....

But it makes i 'global scope' ...so like this, is it really still a closure ? Don't know... Javascript quirk ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment