I get an infinite loop because of this small bit of code. It bees 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");
}
}
I get an infinite loop because of this small bit of code. It bees 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");
}
}
Share
Improve this question
asked May 29, 2012 at 12:17
VadoffVadoff
9,4197 gold badges45 silver badges39 bronze badges
5
- 1 No infinite loop here. Prints 'hi' once (Chrome 19.0.1084.52 m) – KooiInc Commented May 29, 2012 at 12:21
- Seems to run fine for me. NO INFINITE LOOPS!!! – Clyde Lobo Commented May 29, 2012 at 12:21
- 1 Have you simplified the example before posting here? The code given (with no context) runs fine. – diolemo Commented May 29, 2012 at 12:23
-
2
Maybe there is an
i
declared somewhere else and modified in the actual body of your loop? – wnrph Commented May 29, 2012 at 12:24 - I've figured out what was going wrong, it wasn't an infinite loop within the for loop itself, but the infinite calling of the function which contained it. This was due to my function being called within a for loop that also used the var i, and the for loop within my function kept modifying that value so the for loop that called my function would never exit. – Vadoff Commented May 29, 2012 at 22:24
3 Answers
Reset to default 5Since 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.
The code seems to be just fine, see it in action on jsFiddle here.
Another note: Be careful with variables in javascript. You should always use var
to declare them; if you forget that they'll end up being globals!
It shouldn't be infinite but here is the case that might happened.
You are accessing i without declaring var means you are using it as a global variable not local. Try to analyse your code carefully to find out any global 'i' or 'num' that is messing around your loop.