In an answer to this question, I can see the value of i
being retained by sort of throwing it into another function:
var funcs = [];
function createfunc(i) {
return function() { console.log("My value: " + i); };
}
for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
http://jsbin.com/raxifitaberu/1/edit
Why does the function createfunc()
need to return another function? Why is that any better than just returning the string:
var myArray = [];
function createFunc(i){
return "My value: " + i;
};
for (var i = 0; i < 5; i++){
myArray[i]=createFunc(i);
}
console.log(myArray[0]);
console.log(myArray[1]);
console.log(myArray[2]);
http://jsbin.com/demiloronohe/1/edit
Is there some advantage to putting function behind the return
?