Today I Learned

hashrocket A Hashrocket project

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
See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.