The example is not correct? ES6: Scopes of var and let

Can someone help me understand why the variable printNumTwo is supposed to be equal to 3 and not 2?

In the example text for this challenge, the code snippet is given below:

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

It is stated that, “As you can see, printNumTwo() prints 3 and not 2. This is because the value assigned to i was updated and the printNumTwo() returns the global i and not the value i had when the function was created in the for loop.”

I don’t understand why printNumTwo would not be equal to 2. I thought the variable printNumTwo only gets assigned a specific value once and that is when i === 2. printNumTwo is never set equal to a specific value at any other time, regardless of i, correct?

Thank you in advance!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3559.6 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

Thank you for your response!

I am familiar with Java and C, but am new to JavaScript. I believe I have never ran across a block of code like this:

printNumTwo = function(){
      return i;
    };

I believed I understood this code, but I am beginning to think not. Perhaps me being unfamiliar with the step by step execution here is causing my misunderstanding.

I thought that printNumTwo is only tied to i at the moment i = 2, and not at any other moment.

Thank you for your in depth response. I will look into IIFE’s. I feel like I should understand why the code returns links together printNumTwo and i when i is 3 and not only in the third iteration of the for loop.

I really appreciate your thorough responses!