In javascript , inner function always have access to their outer function variable even after the outer function is finished executing. This behaviour is called Closure.
In first snippet, you're iterating over 3 times and pushing the function inside an array.When the loop is finished executing your variable i is set to 4. And function you pushed inside the array has access to this variable . So no matter at what index of array you execute the function you always get 11 ( 4 + 7).
In Second snippet , you are using an self executing anonymous function to hold the value of i . This anonymous function gets immediately executed with every interation . Because of closure function defined inside this anonymous function has a reference to new value of i every time.
So you have a three function inside the array each with seperate value of i (1,2,3)
Writing second snippet as follows makes it more clear
var createAdders = function(){
var fns = [ ];
for (var i=1; i<4; i++) {
(function(a) {
fns[a] = (function(n) {
return a+n;
});
})(i)
}
return fns;}
In javascript you can have function as return value.
and secondly arrays can store function inside themself.
What your doing in code is pushing a function inside array which accepts a single argument and later invoking it.
adders[1](7);
can be broken down as follow
var fn = adders[1];
fn(7); //thats how n is set to 7