2
function a() {
    var n1 = 0,
        n2 = 0;
    for (; n1 < 100; n1++) {
        for (; n2 < 100; n2++) {
            console.log(2);
        }
        console.log(1);
    }
}
a();

function b() {
    for (var n1 = 0; n1 < 100; n1++) {
        for (var n2 = 0; n2 < 100; n2++) {
            console.log(2);
        }
        console.log(1);
    }
}
b();

As you can see.Two simple nested loops,and it looks like they will have the same output.But what puzzles me is that function a() does not output expected result,it loops outside and inside 100 times respectively.What's the difference?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Veitch K
  • 37
  • 5
  • In `function a` the variable `n2` is initialized at the beginning and never after it is reseted to 0 while you do reset `n2` in b() overtime you enter your second loop – Frederic Henri Oct 15 '15 at 07:03

3 Answers3

4

In your b() function n2 variable is created (see @jfriend00 comment) reset during every a loop iteration. It is set to 0 and therefore the b loop goes the whole length (100 times).

In a the variable n1 is created once before the inner loop, so after first a iteration (and 100 b), n2 has a value of 100. In the second a interation n2 is checked if it's less than 100. It's not, so the inner loop ends before it even started.

slomek
  • 4,873
  • 3
  • 17
  • 16
  • 3
    Not exactly right. The n2 variable is only ever ***created*** once due to variable hoisting. The difference in behavior is because `n2` is reset to `0` inside the `n1` loop in the second scenario. – jfriend00 Oct 15 '15 at 07:08
3

First, lets clear up the variable declarations - hoisting and function scope means that both functions look something like this

function a() {
  var n1;
  var n2;
  n1 = 0;
  n2 = 0;
  for (; n1 < 100; n1++) {
    for (; n2 < 100; n2++) {
        console.log(2);
    }
    console.log(1);
  }
}
a();

function b() {
  var n1;
  var n2;
  for (n1 = 0; n1 < 100; n1++) {
    for (n2 = 0; n2 < 100; n2++) {
        console.log(2);
    }
    console.log(1);
  }
}
b();

Now it should be more obvious - function b sets n2 to zero at the start of every for loop, function a does not. If this behavior surprises you, then read more about function scope in JavaScript.

Variable Scope

Community
  • 1
  • 1
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53
2

in a() n2 only inited once, but in b() inited every time n1 changes

Josh Lin
  • 2,397
  • 11
  • 21