0

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]()
Dat Pham
  • 31
  • 7
  • Every function has access to outer variables, no matter how they are declared. It's just that with `var` you have only one variable that will have the value `5` when you call the function, while with `let` every loop iteration has its own variable that doesn't change. – Bergi Aug 06 '22 at 09:53
  • I thought the declarations of `i`s as `var`s are replaced with literal values of each statement in the function declaration, as the elements of the array as: `console.log`, `console.log(0)`, `console.log(1)`, `console.log(2)`, `console.log(3)`, `console.log(4)`. However, its not as my expected – Dat Pham Aug 06 '22 at 10:01
  • No, a closure really has access to the variable itself, and its *current value* - and it can even assign a value to the variable. – Bergi Aug 06 '22 at 10:04

0 Answers0