Var variable used in loops

Can someone explain to me more in detail why the console.log result here is 3?

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

I don’t understand why it is 3 if the code explicitly says to return i only if i === 2. So why would it return 3??

Taken from this lesson: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

Many thanks.

On your for loop, try using let i instead of var i

1 Like

The code does not say ‘return i if i is 2’. The code says ‘define the function printNumTwo if i is 2’. But var will hosit the declaration outside of the scope where it was defined use the same variablei for the entire function scope. (Edit because @chuckadams descption is more accurate. I was getting it a bit mixed up) When printNumTwo is called, i was already incremented to 3.

1 Like

When you use var foo, then there is only one foo variable for the entire function, whether it’s part of a loop or not. Every one of those functions shares the same variable. When you use let, it creates a new variable each time through the loop, so each instance of that inner function gets a fresh copy.

Creating functions like this in a loop is something you normally Would Never Do, but it does sometimes happen accidentally, when creating a bunch of event handlers for instance. The solution is pretty simple: never use var, always use const and let instead.

2 Likes

So am I correct in understanding that the result of 3 when using var is because after the last i++ , i became 3 and just stayed like that?

And when we use let, the result is 2 because the code stopped running once it saw the if statement and so stayed at i = 2?

Sorry I am just confused about how it physically works, step by step through the loop and in exactly what way it’s different for let and var

The code does not stop running at the if statement in either case.

This is what’s going on. The code continues to run, but the printNumTwo function retained the version of i set to 2 instead of the incremented quantity like with var.

1 Like

But why does the printNumTwo function retain the i set to 2 version? Why does var not retain it and does the increment? I don’t understand the logic

When chuckadams said everyone of those functions shares the same variable, do you mean that i is always 3? What do you mean by the same?