Javascript closures bind to the variable
If you're a clever kind of javascript dev you create functions with variables from outside the function definition.
var i = 5;
function printSomething() {console.log(i);}
printSomething();
> 5
But you should watch yourself when using a closure within a loop.
> fns = []
> for(var i = 0; i < 3; i++) {fns.push(function () {console.log(i); })};
> fns[0]();
3
> fns[1]();
3
> fns[2]();
3
Yikes! The closure references the variable as it is now, not the variable as it was. You should only reference the variable if you don't expect it to change (or if you want it to change).
> fns = []
> function createFn(i) { return function() { console.log(i); };}
> for (var i = 0; i < 3; i++) {fns.push(createFn(i))};
> fns[0]();
0
> fns[1]();
1
> fns[2]();
2
Tweet