while()
, for()
, or do…while()
loop, there's always the danger that the loop will never terminate. This is called an infinite loop, and it has been the bugbear of programmers for as long as people have been programming. Here are some notes to bear in mind to help you avoid infinite loops:
- The statements in the
for()
block should never change the value of the loop counter variable. If they do, then your loop may either terminate prematurely or it may end up in an infinite loop. - In
while()
anddo…while()
loops, make sure you have at least one statement within the loop that changes the value of the comparison variable. (That is, the variable you use in the loop's comparison statement.) Otherwise, the statement might always returntrue
and the loop will never end. - In
while()
anddo…while()
loops, never rely on the user to enter a specific value to end the loop. She might cancel the prompt box or do something else that prevents the loop from terminating. - If you have an infinite loop and you're not sure why, insert one or more
debugger
and/orconsole.log()
statements within the loop statement block to display the current value of the counter or comparison variable. This enables you to see what happens to the variable with each pass through the loop.