To avoid such problems, make sure to properly initialize the counter, make sure the terminating condition is eventually met with the proper updates to the counter variable.
Consider the following infinite for loop.
for (j = 100; j >= 5; j++)
Do you know why is this an infinite for loop? Note that j is initialized to 100 and each time the loop is executed, we add 1. Thus, each time the for loop will execute the value of j will go up by 1, it will never reach 5, our stopping condition.
Consider the following infinite while loop.
let i = 2;
while (i <= 10) {
document.write (i + "<br>");
i -= 2;
}
In the above while loop, i will always remain less than 10 because each time the loop will be executed, i will be decremented by 2.
<aside> ⚖️ Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact [email protected] for inquiries.
</aside>