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;
}Answer:
The problem here is when we are trying to execute the function that was created, the value of 'i' will always be equal as the argument 'y'.
createArrayOfFunctions(3)[0](3) // should be 3 but turn out to be 6
createArrayOfFunctions(3)[1](3) // should be 4 but turn out to be 6
createArrayOfFunctions(3)[2](3) // should be 5 but turn out to be 6The reason is that the closures of all these three functions are sharing the same lexical environment.The quickest way to solve this problem is to use const / let instead of var, which makes each closure pointing to the block scope variable, i.
function createArrayOfFunctions(y) {
var arr = [];
for (let i = 0; i < y; i++) {
arr[i] = function(x) {
return x + i;
}
}
return arr;
}