Hi I am new to javascript and I cannot understand the following code:
var createAdders = function () {
var fns = [];
for (var i = 1; i < 4; i++) {
fns[i] = (function (n) {
return i + n;
});
}
return fns;
}
var adders = createAdders();
adders[1](7); //11 ??
adders[2](7); //11 ??
adders[3](7); //11 ??
From what I understand 7 is being passed as an argument but createAdders()
doesn't assign 7 to any variable so does that mean 7 is being passed to the very next function within createAdders()
i.e the anonymous function and assigned to the variable n
.
Is my logic correct?
The code above does seem to work but for every call the result is 11. I found this code in a very reliable blog as an example to a situation where closures would be useful.The above code is then altered in the following way to cite the advantages of closures.
var createAdders = function () {
var fns = [];
for (var i = 1; i < 4; i++) {
(function (i) {
fns[i] = (function (n) {
return i + n;
});
})(i) //// why is (i) used here? what purpose does it serve??////
}
return fns;
}
var adders = createAdders();
adders[1](7); //8
adders[2](7); //9
adders[3](7); //10
Is the same logic applied here as well?
I need to understand how n is being assigned the value 7
Why is (i) being used at the end of the function in the new code?