3 ms·
But closures still hold references to variables, even if they are numbers. let counter = () => { let i = 0 return () => { ++i; return i } }
by mbrock 6y ago
But closures still hold references to variables, even if they are numbers.
let counter = () => {
let i = 0
return () => { ++i; return i }
}
let x = counter()
console.log(x(), x(), x()) // 1 2 3
If you reimplement the OP's for (let i...) loop with a loop where the i variable is declared before the loop, you will get the behavior OP mentioned.