Search code examples
javascriptjsbin

Javascript loop with alert


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.


Solution

  • 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).