I expect the calling of the first element in the array to print out the number 0. However, it prints 5. Does the function call have access to i
of its parent function because I declare i
as var
? If I declare i
as a let
variable, it prints 0 as expected.
0-closureBug.js
function makeFunctionArray() {
const arr = []
for (var i = 0; i < 5; i++) {
arr.push(function() { console.log(i) })
}
console.log(i)
return arr
}
const functionArr = makeFunctionArray()
functionArr[0]()