Function inside for loop

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.

  1. assign variable printNumTwo to the global scope (since you’re using var)
  2. enter the for loop and assign the global variable i and set it to 0
  3. run the for loop and console.log every value for i
  4. if i === 2 console.log
  5. if i === 2 assign printNumTwo to the inner function
  6. store a reference to the global variable i inside printNumTwo
  7. exit the loop when the global i === 3
  8. console.log("ans: ",printNumTwo()) the current value of i

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 i in 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.