Could you please help me out?

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3
  1. what’s the purpose for if condition here?
    2)when i=3, the how the “if Condition is bypassed” and " return i" gives 3?

i am stuck here since two days but cant get it. Please help me out with the flow.

The purpose of this lesson is to teach the importance of correctly scoping your variables.

With the if(i ===2) you would expect printNumTwo to print the number two because it is initialized when i is 2 BUT printNumTwo doesn’t print the number 2, it prints the variable i and the variable i is changed to 3 at the end of the for loop. So even though i was 2 when printNumTwo was initialized, it will always print whatever the current value of i is.

hi there, maybe change i===2 to i == 2 and i < 3 to i < 2

it’s awesome you want to help! though this was a question on a specific freeCodeCamp challenge, you can see this code in the description of this challenge:

ES6: Compare Scopes of the var and let Keywords

Declare variable i with “let” not with "var " that’s resolve by ES6.

Thanks for your encourage words, I forgot that it was in ES6 lesson. I’m better come back to code camp and learn asap.