Compare Scopes of the var and let Keywords - Last example

I went through all examples and I think I get it, until the last one. The explanations doesn’t make total sense to me:

i is not defined because it was not declared in the global scope. It is only declared within the for loop statement.

  • Fair enough, I get that part

printNumTwo() returned the correct value because three different i variables with unique values (0, 1, and 2) were created by the let keyword within the loop statement.

  • That I don’t get.
  • Within the FOR loop, ‘i’ takes values 0 for first run, then 1, then 2, then 3 at which point the condition i < 3 is not verified and the loop finishes.
  • printNumTwo is assigned a function that returns i when i = 2
  • I don’t understand why the explanation says that 3 different ‘i’ with unique values (0,1 and 2) were created

Many thanks in advance for your feedback and keep up the good code! I love it but need to practice a lot mooore!

1 Like

When using var, i is only evaluated when it is actually used. When using let inside the for loop declaration, JavaScript “remembers” the value of i where it is referenced, so that when it is later used, the “remembered” value is used.

Why? Because let creates its own scope (i.e between the { and } of the for loop block.

1 Like

Thanks @camperextraordinaire! Much appreciated!