How can I avoid an infinite loop with a `while` condition?
Quick answer
A while loop repeats as long as its condition is true, checking that condition before each pass. To make a counter loop stop, initialize the counter, compare it with a clear limit, and update it inside the loop so it can reach that limit. For example, while (count < 5) stops when count becomes 5, provided each pass increments count.
The question, the details, the next step.
A practical checklist
Write down the value that the
whilecondition checks.Choose and initialize a starting value before the loop.
State the stopping condition in plain language.
Update the relevant value inside each pass, moving it toward the stopping point.
Trace a few passes and confirm the condition eventually becomes false.
A few more useful answers
Does `while` check its condition before or after the loop body?
Before each pass. If the condition is false at the first check, the body does not run. [S1]
Can a loop stop if its body does not change the counter?
Not if the condition stays true and no other relevant state changes. In a counter loop, update the counter so it can reach the stopping point. [S1]
Does this counter example prove that any `while` loop will stop?
No. It shows why this particular bounded counter loop stops. Other loops need their own condition and progress checked.
Sources
References used for this guide.
- [S1] while — JavaScript | MDN developer.mozilla.org · Checked
