Home

How to Avoid Infinite Loops in JavaScript

|
|  Updated:  
2018-07-09 19:16:40
HTML & CSS Essentials For Dummies
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 Google® Workspace administrator, a thankless job if ever there was one. Paul is also a full-time technical writer who has somehow found the time to write more than 100 books that have sold more than four million copies worldwide.