Web Coding & Development All-in-One For Dummies
Book image
Explore Book Buy On Amazon
Whenever you use JavaScript to program a 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() and do…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 return true and the loop will never end.
  • In while() and do…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/or console.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.

About This Article

This article is from the book:

About the book author:

Paul McFedries is a true renaissance geek. He has been a programmer, consultant, database developer, and website builder. He's also the author of more than 90 books including top sellers covering Windows, Office, and macOS.

This article can be found in the category: