While and Do...While Loops
A while loop repeats a block of code for as long as a condition is true. It suits work where the number of passes is not known in advance, such as reading until a queue is empty or retrying until something succeeds. A do...while loop does the same, except that it checks the condition after each pass, so its body always runs at least once.
The condition is checked before every pass, including the first:
let savings = 0;let weeks = 0;
while (savings < 100) { savings += 30; weeks++;}console.log(`${weeks} weeks, saved ${savings}`);This prints:
4 weeks, saved 120Something inside the loop must eventually make the condition false. Here savings grows on every pass, but a loop whose condition never changes runs forever and freezes the page or the program.
A common use is to keep taking items from an array until none are left:
const inbox = ['invoice', 'newsletter', 'receipt'];
while (inbox.length > 0) { const message = inbox.shift(); console.log(`filing ${message}`);}console.log(inbox);This prints:
filing invoicefiling newsletterfiling receipt[]do…while
Section titled “do…while”do...while runs the body first and checks the condition afterwards. When the condition is false from the start, a while loop does nothing, but a do...while loop still runs once:
let stock = 0;
while (stock > 0) { console.log('while: selling one'); stock--;}
do { console.log('do...while: checked once');} while (stock > 0);This prints:
do...while: checked onceThat makes it the natural fit when the value being tested is produced by the body, such as asking a question until the answer is valid. Here a list of replies stands in for a user’s input:
const replies = ['', 'maybe', 'yes'];let attempt = 0;let answer;
do { answer = replies[attempt]; attempt++; console.log(`attempt ${attempt}: "${answer}"`);} while (answer !== 'yes' && answer !== 'no');This prints:
attempt 1: ""attempt 2: "maybe"attempt 3: "yes"answer is declared outside the loop, because a variable declared with let inside the body is not visible to the condition after it.
Leaving a loop with break
Section titled “Leaving a loop with break”break ends a while loop at any point. That allows a loop written as while (true), which has no condition of its own and stops only when the body decides to:
let level = 1;
while (true) { level *= 2; if (level > 20) { break; } console.log(level);}This prints:
24816This form is useful when the check to stop sits in the middle of the body rather than at either end. continue also works in both kinds of loop, and skips straight to the next check of the condition.
Steve Griffith covers this topic in his video JavaScript While and Do..While Loops.