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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With