While and Do While Loops
The while loop repeats a block as long as a condition is true. Use it when you don't know in advance how many rounds you need: keep applying payments until the balance reaches zero, keep reading pages until there are no more, keep doubling a value while it is under a limit. The do...while loop is the same, except it always runs the body at least once.
In One Minute
while (condition) { ... }checks the condition before each round; the body may run zero times.do { ... } while (condition);checks after each round; the body runs at least once.- Something inside the body must eventually make the condition false, or the loop never ends.
- Use
forwhen you can count the rounds; usewhilewhen you wait for something to change.
The while Loop
Syntax
while (condition) {
// runs while condition is truthy
// must change something so condition eventually becomes falsy
}Example
A balance of $450 is paid off with monthly payments of $120. How many months does it take?
let balance = 450;
let months = 0;
while (balance > 0) {
balance -= 120;
months++;
console.log(`After month ${months}: $${balance}`);
}
console.log(`Paid off in ${months} months`);After month 1: $330
After month 2: $210
After month 3: $90
After month 4: $-30
Paid off in 4 monthsExplanation: the loop doesn't know the number of months in advance. It keeps going while there is a balance. In month 4, the payment is more than what was left, so the balance goes negative (an overpayment of $30) and the condition becomes false. The In Practice example below handles the last payment properly.
The do...while Loop
Syntax
do {
// runs once, then again while condition is truthy
} while (condition);Note the semicolon after the condition. The difference from while matters only when the condition is false from the start:
let attempts = 0;
while (attempts > 0) {
console.log("while body ran");
}
do {
console.log("do...while body ran");
} while (attempts > 0);do...while body ranExplanation: attempts is 0, so the condition is false immediately. The while body never runs. The do...while body runs once before the condition is checked.
do...while fits "do it, then decide whether to repeat" situations, such as asking for input until it is valid, or fetching the first page of results and continuing while there are more.
Infinite Loops
An infinite loop never ends because its condition never becomes false. In a browser, it freezes the tab; in Node.js, the program hangs until you press Ctrl+C.
let count = 0;
while (count < 5) {
console.log(count);
// forgot count++: count stays 0 forever
}Common causes:
| Cause | Example |
|---|---|
| The variable in the condition never changes | Forgetting count++ |
| It changes the wrong way | count-- when the condition is count < 5 |
| It skips past the stopping value | while (x !== 10) x += 3; (goes 0, 3, 6, 9, 12, ...) |
The condition is always true on purpose, but there's no break | while (true) { ... } |
A deliberate while (true) loop is fine when the body has a clear break, as the next lesson shows. To stop a frozen browser tab, close it; to stop Node.js, press Ctrl+C. The Try it runner on this site stops any example after a few seconds.
Sentinel Loops
A sentinel is a special value that means "stop". Loops that read data often run until they meet it: an empty line, a null page, the end of a list.
const pages = [["Navika", "Srihitha"], ["Advitha"], null];
let pageNumber = 0;
let page = pages[pageNumber];
while (page !== null) {
console.log(`Page ${pageNumber + 1}:`, page.join(", "));
pageNumber++;
page = pages[pageNumber];
}
console.log("No more pages");Page 1: Navika, Srihitha
Page 2: Advitha
No more pagesThis shape (read, test, process, read the next one) is how scripts walk through paged API results. In real code, each page comes from a fetch call; the async chapter shows that version.
In Practice
The payment schedule again, this time making the last payment exactly what is left, and capping the loop at 6 months (a real schedule might allow 24) as a safety net so bad input can't cause an infinite loop:
function schedule(balance, monthly) {
const MAX_MONTHS = 6;
let month = 0;
while (balance > 0 && month < MAX_MONTHS) {
month++;
const payment = Math.min(monthly, balance);
balance -= payment;
console.log(`Month ${month}: pay $${payment}, left $${balance}`);
}
if (balance > 0) console.log(`Still $${balance} due after ${MAX_MONTHS} months`);
}
schedule(450, 120);
schedule(100, 0);Month 1: pay $120, left $330
Month 2: pay $120, left $210
Month 3: pay $120, left $90
Month 4: pay $90, left $0
Month 1: pay $0, left $100
Month 2: pay $0, left $100
Month 3: pay $0, left $100
Month 4: pay $0, left $100
Month 5: pay $0, left $100
Month 6: pay $0, left $100
Still $100 due after 6 monthsExplanation: with a monthly payment of $0, the balance never shrinks. Without the month < MAX_MONTHS guard, the second call would loop forever. The better fix is to reject a zero payment before the loop starts, but a maximum-rounds guard is a cheap second line of defense in any loop driven by outside data.
Common Mistakes
Forgetting to update the condition's variable. The loop never ends. Check that every path through the body moves toward the exit.
Using while where for fits. If you count from a start to an end, a for loop keeps the counter, condition and update in one line where they can't be forgotten.
Missing semicolon after do...while. } while (x < 3) without ; usually works thanks to automatic semicolon insertion, but the semicolon makes the end clear.
Off-by-one in the condition. while (balance >= 0) runs one extra round when the balance hits exactly 0.
Practice
Challenge: Starting from $100 in savings that grows by 10% a year (rounded to whole dollars with Math.round), use a while loop to find how many years it takes to reach at least $200. Print each year's amount.
Show solution
let amount = 100;
let years = 0;
while (amount < 200) {
amount = Math.round(amount * 1.1);
years++;
console.log(`Year ${years}: $${amount}`);
}
console.log(`Reached $200 in ${years} years`);Year 1: $110
Year 2: $121
Year 3: $133
Year 4: $146
Year 5: $161
Year 6: $177
Year 7: $195
Year 8: $215
Reached $200 in 8 yearsKey Takeaways
| Loop | Checks | Minimum rounds |
|---|---|---|
for | Before each round | 0 |
while | Before each round | 0 |
do...while | After each round | 1 |
Was this tutorial helpful?