Why display the value 3?

Compare Scopes of the var and let Keywords

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

\\ How does this code work?

There is a lengthy explanation on the page - can you read that and then be more specific with your question?

I read the explanation on that page. But I still don’t understand and I want to know how the function works.

Once the loop has finished the value of i is 3, and printNumTwo() returns the value of i, which is 3 at the point at which it’s called.

How? variable i cannot enter a for loop when it’s equal to 3.

That means when the loop is finished, i is 3 → because that is the condition for the loop to finish.
The point of var is, that it create a global variable - meaning one that exists outside of all the code. So because printNumTwo is returning “i”, it will reference the global variable.
However “let” doesn’t create a global value and it doesn’t update the value of “i” → it actually creates a new “i” in every loop. So when the function is defined, it will reference the “i” that was created in the loop the function was created.
You can see this by adding another function:

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

Even though both functions “return i”, it’s actually NOT the same “i”, but a completly different entity within the code.

i++ happens after every iteration BEFORE checking the condition, this is how the “for” loop works.

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