DEV Community

Randy Rivera
Randy Rivera

Posted on

Preventing Infinite Loops With a Valid Terminal Condition

  • The final topic is the dreaded infinite loop. Loops are great tools when you need your program to run a code block a certain number of times or until a condition is met, but they need a terminal condition that ends the looping.
  • It's the programmer's job to ensure that the terminal condition, which tells the program when to break out of the loop code, is eventually reached.
  • Ex: The myFunc() function contains an infinite loop because the terminal condition i != 4 will never evaluate to false (and break the looping) - i will increment by 2 each pass, and jump right over 4 since i is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for i less than or equal to 4.
function myFunc() {
  for (let i = 1; i != 4; i += 2) {
    console.log("Still going!");
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function myFunc() {
  for (let i = 1; i <= 4; i += 2) {
    console.log("Still going!");
  }
}
myFunc();
Enter fullscreen mode Exit fullscreen mode
  • i starts at 1. i which is 1 first is less than or equal to four so we continue forward. i is now 3 because i will increment by 2 each pass. 3 is less than or equal to four so we continue. i is now 5. 5 isnt less than or equal to four so we stop a the console will display
Still going!
Still going!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)