Globally and Locally Scopes

Could anyone tell me why this code get 3 ?
loop 0, 1, 2 but how come 3 ??


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

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

The i variable takes 3 as its last value, because it’s the value that fails the for-loop condition.

1 Like

I don’t understand Why does i takes 3 as its last value ? can you explain a little bit more

i starts at 0. Then it checks if i < 3, which is true, so it proceeds to run the loop once. After all that, i++ runs, so i is now 1.

Then it checks again if i < 3. Again it’s true, and runs the loop again. Then i is incremented to 2.

Then it checks again if i < 3. Again it’s true, and runs the loop again. Then i is incremented to 3.

Then it checks again if i < 3. Now this is false, because 3 is not less than itself. The for-loop stops, then the console.log is ran. The function uses that last value of i, and you get 3.

I understand the concept of loop (it loop until the condition no longer true) please check the code below for me

var printNumTwo;
for (var i = 0; i < 3; i++) {
// console.log(i) get 0, 1, 2   exactly what i expected 
  if(i === 2){   // but here the if statement what does it mean ?, (if i === 2) then run printNumTwo function which return i ? 
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// 3

ps. I already passed this challenge and i understand how does globally and locally of variable declaration works but this code i’m asking still stuck in my mind bcoz it still doesn’t make sense for me right now

It’s true that printNumTwo gets assigned that function when i is 2. But it doesn’t mean that the printTwoNum function will return 2. It will return whatever the value of i is when you call it. Before you called printNumTwo in the last line, the i variable takes the value of 3, as per for-loop mechanics (try console.log(i) immediately after the for-loop). So that’s what the function returns.

1 Like

Perhaps to supplement, the code inside the function is executed after function invocation not after declaration. You can declare a function but if you don’t invoke it, it won’t execute. The if condition in the for loop evaluates to true when i = 2 and then assigns the function expression to the global variable PrintNumTwo
but doesn’t execute. The if loop continues until i is 3 then the function is invoked when the for loop is exited. Why is the i still accessible outside the for loop? It’s because its declaration is hoisted to the top of the scope. Meaning it’s a global variable as well because you have used var keyword for declaring it.