This is due to closures. Essentially in javascript, unlike other languages, functions have access to anything in their scope after they return.
So what happens when you use var is that the variable is bound to the global scope, and every function has access to it. When we finally call printNumTwo, it still can only access the global i at the moment you call it, which will be 3, since the loop ends when it reaches 3.
I find it helps me to walk through how the js engine runs this code, line by line.
- assign variable
printNumTwoto the global scope (since you’re usingvar) - enter the for loop and assign the global variable
iand set it to 0 - run the for loop and
console.logevery value fori - if
i === 2 console.log - if
i === 2assignprintNumTwoto the inner function - store a reference to the global variable
iinsideprintNumTwo - exit the loop when the global
i === 3 -
console.log("ans: ",printNumTwo())the current value ofi
At step 8 the the value of the global i is 3, and the reference inside printNumTwo is mutated (changed). So that’s what gets logged.
Using es6 this is easily solved by using let whenever you intend to reassign a variable. let is bound to the function scope that sets it. Therefore step 6 changes and instead does
- store a reference to the local variable
iin the inner function (which is equal to 2 at this point)
Then at step 8, printNumTwo has access to the value of i when it was assigned.
Hope that helps. Closures take a while to understand sometimes.