//createArrayOfFunctions
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
arr[i] = function(x) { return x + i; }
}
return arr;
}
We plan to use the Javascript function above to create an array and fill value for each elements of it but the function doesn't work as expected. To correct it, we need the help of closure. The function is rewritten as following:
//Fix bug in create array function
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
arr[i] = function(x) { return x + i; }(i);
}
return arr;
}