Please explain what is the bug in the following Javascript function, and how to correct it.
function createArrayOfFunctions(y) {
var arr = [];
for (var i = 0; i < y; i++) {
arr[i] = function(x) {
return x + i;
};
}
return arr;
}
The bug above is that "the i
s" in each function in the array is referencing to "that i
" inside the for
loop.
The function sum
now encapsulates/stores a local variable index
, and it returns a child function which can then reference index
from its parent's scope, rather than that of the for loop.
// Assume y >= 0 and is an integer
function createArrayOfFunctions(y) {
var arr = [];
for (var i = 0; i < y; i++) {
var sum = function() {
var index = i
return function(x) {
return x + index
}
}
arr[i] = sum()
}
return arr;
}
var funcs = createArrayOfFunctions(5)
// Test cases
console.log(funcs[0](7)) // 7
console.log(funcs[1](7)) // 8
console.log(funcs[2](7)) // 9