Preventing Infinite Loops With a Valid Terminal Condition
Randy Rivera
Posted on May 8, 2021
- 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!");
}
}
- Answer:
function myFunc() {
for (let i = 1; i <= 4; i += 2) {
console.log("Still going!");
}
}
myFunc();
- 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!
💖 💪 🙅 🚩
Randy Rivera
Posted on May 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Creating a globe map with visibility features in TypeScript and working with 3D maps globes
April 10, 2024
javascript AWS Cognito Passwordless Implementation: For Bonus, add Hasura Claims in the Token.
February 9, 2022