Why is this javascript for loop running only once?

Kam picture Kam · May 28, 2014 · Viewed 12.3k times · Source
function f1() {
   for (i = 0; i <= 5; i++)
      console.log(i);
}
function foo() {
   for (i = 0; i < 5; i++)
      f1();
}
foo();

Hi, I'm trying to understand why the result of executing foo is:

0
1
2
3
4
5

And not:

0
1
2
3
4
5
0
1
2
3
4
5
0
1
2
3
4
5
0
1
2
3
4
5
0
1
2
3
4
5

It's a slide I am reading about JS and its talking about when you don't use var then it is defined on the global object and provides this example without any further details why we get the result.

I thought it will simply loop and run the f1 function each time until its less than 5.

Please help me understand.

Thanks

Answer

Cerbrus picture Cerbrus · May 28, 2014

The problem is in your iterators (i):

for (i = 0; i <= 5; i++)

i is global, and both your for loops test against it, making them only run once, and aborting when i == 5.

So, what happens is this:

When you call foo(), foo tells the js interpreter to create a variable in the global scope called i, and set it to 0. Then foo calls f1.
There, the for loop sets i, which already exists, to 0, and runs it's loop like it should, incrementing i up to 5.
Then, it's time for the second iteration of the loop in foo, so it checks if i < 5, but it's not (i==6 (5 from f1, +1 from foo)), so it will not call f1 again.

To fix this, either declare them in the function's local scope using var:

function f1() {
    for (var i = 0; i <= 5; i++)
        console.log(i);
}
function foo() {
    for (var i = 0; i < 5; i++)
        f1();
}
foo();

Or, use different variables:

function f1() {
    for (i = 0; i <= 5; i++)
        console.log(i);
}
function foo() {
    for (j = 0; j < 5; j++)
        f1();
}
foo();

However, this second option is a bad idea, since it will both place i and j in the global scope, which is asking for conflicts. I'd suggest using the var option.