Nature of for loop and printNumTwo = function() statement meaning

People of freeCodeCamp i don’t understand the behaviors of " for loop ".
Please comment on my understanding of " for loop " whether i understood correct or not.

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3
My Understanding on foe loop : 

1. First " i" initialize to 0;
2. After than i checked with 3 whether less then or not if condition is true then it start executing code of inside the " for loop ".
3.  After the completion on code inside the " for loop ".The value of " i " variable is incremented by " i++ ".
4. Repeat Above process with updated i value until condition is false.

But I don’t understand why this code return 3 :slight_smile:

And What is the meaning of " printNumTwo = function() ; " code.

Your understanding of how a for loop works is correct.

In fact this example is there to show you that the loop has not stopped at 2, but had to execute the update condition (i++) thus incrementing the value.

so in words it would be

 - initialize an empty variable "printNumTwo"
 - define and run a for loop

   - i = 0 -> do nothing / i = 1 -> do nothing
   - i = 2 -> assign to "printNumTwo" a function which 
              purpose is to print the value of i

   - i = 3 -> condition turn false, exit loop

By looking at the code we know that printNumTwo is now a function, but the developer has made a logic mistake by thinking that
because the condition was i === 2 the function will print 2 (thus the name)

The function is in fact printing 3 because the for loop has executed the updater before moving on.

Hope this clarify things up :wink:

1 Like

This is really about variable scope, more than anything else. You are correct in assuming that i is in fact 2 when the printNumTwo function is created. However, that variable is global and when the function is called after the loop is done the value of i is what it ended at (3), not what it was when the function was created (2).

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

Here it is using a while loop where the scope of the variable is a little more obvious.

var printNumTwo;
var index = 0;

while (index < 3) {
  
  if (index === 2) {
    printNumTwo = function() {
      return index;
    };
    console.log(index); // 2
    console.log(printNumTwo()); // 2
  }
  index++;
}

console.log(index); // 3
console.log(printNumTwo()); // 3
index = 42;
console.log(printNumTwo()); // 42