Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript infinite loop caused by simple for loop

I get an infinite loop because of this small bit of code. It becomes fixed if I declared the var i to any value (i.e. var i = 0) before the loop, and I'm not sure why. Could someone who's familiar with javascript's intricacies explain to me what's going on here?

for (num = 1; num <= 2; num++) {
    for (i = 1; i < num; i++) {
      console.log("hi");
    }
}
like image 615
Vadoff Avatar asked Aug 05 '26 22:08

Vadoff


1 Answers

Since i was not declared as a local var, your code is, in-effect altering variables/objects window.i as well as window.num

Adding var keywords should fix the problem:

for (var num = 1; num <= 2; num++) {
    for (var i = 1; i < num; i++) {
      console.log("hi");
    }
}

This doesn't answer the question why the program goes into an infinite loop. But you only know that the hanging code was trying to alter window.i and window.num which might be used elsewhere.

Read more about javascript scoping rules.

like image 103
Kayo Avatar answered Aug 08 '26 11:08

Kayo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!