1

Hi I'm confused with alert and console.log

var count = [];

function iterate(number) {
  count.push(number);
  for (i = 0; i < count.length; i++) {
    console.log(count[i]);
  }
}

iterate(2);
iterate(3);
iterate(4);

Console will give me 2,2,3,2,3,4 but when I change console.log(count[i]) to alert(count[i]); it will repeat just 2 three times, why?

var count = [];

function iterate(number) {
  count.push(number);
  for (i = 0; i < count.length; i++) {
    alert(count[i]);
  }
}

iterate(2);
iterate(3);
iterate(4);

It doesn't do that above, but it does on JSBin.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Side note: It's not causing a problem in the above, but the code is falling prey to [The Horror of Implicit Globals](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *(that's a post on my anemic little blog)*. Declare `i` in `iterate`. – T.J. Crowder Apr 17 '17 at 15:01
  • I'm confused, how? I thought alert inputs the elements of the count array, whenever I call the function, the length of the array will be increased –  Apr 17 '17 at 15:03
  • I mean when I try it in JS Bin(alert type), it will just alert 2 on the first ,2nd and 3rd call –  Apr 17 '17 at 15:23
  • I've updated my answer. You're running into JSBin's infinite loop protection, which is really aggressive when you're not running the output on its own because it's really easy to create infinitely loops while typing code (JSBin has the option of trying to run your code as soon as you pause typing). – T.J. Crowder Apr 17 '17 at 15:38

1 Answers1

1

Both versions show the same thing.

count starts empty.

On the first call, you push 2 into count so it has [2], and then loop just once (i == 0), outputting count[0] (which is 2).

On the second call, you push 3 into count so it has [2, 3] in it, and loop twice (i == 0, i == 1), showing count[0] (2) and count[1] (3).

On the third call, you push 4 into count so it has [2, 3, 4] in it, and loop three times (i == 0, i == 1, i == 2), showing count[0] (2), count[1] (3), and count[2] (4).


Re your comment:

I mean when I try it in JS Bin(alert type), it will just alert 2 on the first ,2nd and 3rd call

Ah! You're running into JSBin's "infinite loop protection." If you run it here and look in the web console, you'll see

Exiting potential infinite loop at line 5. To disable loop protection: add "// noprotect" to your code

...but if you run the output page of that, it shows the full result.

The alert version triggers the infinite loop protection in the dev mode because it sees the same code happen more than once but more than 100ms apart (because of the delay while you dismiss the alert).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875