ES6 - Compare Scopes of the var and let Keywords

Hey everybody, I have no problem completing this test but have a question about the introduction. This is the current one:

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
console.log(i);

" Here the console will display the value 2 , and an error that i is not defined .

i is not defined because it was not declared in the global scope. It is only declared within the for loop statement. 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."
//////////////////////////////////////////////////////////////////////////

I dont understand why there are only 3 values (0, 1 and 2) because I think it must’ve had the value “3” as well. Why i++ didnt function when i reached the value 2?

Please help me.

Challenge: ES6 - Compare Scopes of the var and let Keywords

Link to the challenge:

“…three different i variables with unique values (0, 1, and 2) were created by the let keyword within the loop statement.”

I think “within the loop statement” means “inside the body of the for loop”. In other words, when the code inside the for loop is executed. The code inside the for loop is never executed when i equals 3, so technically i only equals 0, 1, and 2 inside the for loop.

Could this be written a little clearer? Perhaps. But the real point is that when i equals 2 inside the for loop and the printNumTwo function is defined, the value returned by printNumTwo will in fact be 2 because i was declared using let and thus the value of i at that time is retained.

So technically there were 4 values of i (0,1,2 and 3) but only 0,1 and 2 were within the loop statement, right?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.