Beginner question about global/local variables

Hi, I’m having trouble figuring out something with this code.

for (var i = 0; i < 3; i++) {
  console.log(i);
// returns [0, 1, 2]
}
console.log(i);
//returns 3

I get it why we’ve got 0, 1, 2 inside the function but I don’t get it why we get 3 outside the function. Why doesn’t it show the same result? I figure 3 means there are three values stored inside the i - 0, 1, 2 ?

Try to use the let keyword instead of var for declaring the counter in a for loop. let only has block scope (your for loop) and var has function scope (the function your loop is declared in). In fact, never use var.

Further reading with a few suggestions: https://www.reddit.com/r/javascript/comments/a50jte/is_it_best_to_use_var_or_let_in_for_loop/

1 Like

It’s true you should avoid var for reasons like this, but to address the original question: the for loop’s terminating condition is i < 3. The loop body runs three times, incrementing i when the end of the loop body is reached each time. Then i becomes 3, the loop condition is false, and the loop terminates. Thus, i is 3 after the loop is done.

1 Like

So that’s what’s going on. I was thinking that since the condition was <3 that the 3 will be “discarded” and that the i is left at 2.