while vs do...while loop in JavaScript
Beginner · 3 min read
A loop repeats some code while a condition is true. JavaScript gives you two loops that do this with a small but important difference: while checks the condition before each turn, and do...while checks it after. Most of the time they behave the same. In one case they don't, and that case is where bugs hide.
In this tutorial you will write the same ticket-printing loop both ways, find the input that makes them disagree, and then use do...while for a job that must run at least once, and see what that costs. You need to know what an array is and how push and ++ work.
How each loop runs
A while loop:
- Check the condition. If it is false, stop.
- Run the body.
- Go back to 1.
A do...while loop:
- Run the body.
- Check the condition. If it is false, stop.
- Go back to 1.
The only difference is the order. A while loop can run its body zero times. A do...while loop always runs it at least once, because it doesn't look at the condition until after the first turn.
What they look like
let n = 0;
while (n < 2) { n++; }
console.log(n); // 2
let m = 0;
do { m++; } while (m < 2);
console.log(m); // 2
Notice the semicolon after while (m < 2) in the second loop. It ends the do...while statement, and it is the usual style to write it. A plain while loop has its body after the condition instead, so it has no semicolon there.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
77 while checks first, do...while checks last
easyWrite the same counting loop twice, once with while and once with do...while, then call both with a count of zero. Then use do...while for a job that must happen at least once, and show what that costs.
Stuck? Three hints, smallest first
- 1. A
whileloop can run its body zero times; ado...whilecannot. - 2. Write the count of zero down as a test case, because that is where the two differ.
- 3.
do { } while (cond);keeps its semicolon at the end.
Step 1: print tickets with while
function ticketsWhile(count) {
const printed = [];
let n = 0;
while (n < count) {
printed.push('T' + (n + 1));
n++;
}
return printed;
}
console.log(ticketsWhile(3)); // [ 'T1', 'T2', 'T3' ]
Each turn adds a ticket label and counts up. When n reaches count, the check fails and the loop ends. The function returns the labels instead of printing them, so you can test the result.
Step 2: the same with do...while
function ticketsDoWhile(count) {
const printed = [];
let n = 0;
do {
printed.push('T' + (n + 1));
n++;
} while (n < count);
return printed;
}
console.log(ticketsDoWhile(3)); // [ 'T1', 'T2', 'T3' ]
Same three tickets. So far you can't tell them apart.
Step 3: ask for zero tickets
Here is the input where they disagree:
function ticketsWhile(count) {
const printed = [];
let n = 0;
while (n < count) { printed.push('T' + (n + 1)); n++; }
return printed;
}
function ticketsDoWhile(count) {
const printed = [];
let n = 0;
do { printed.push('T' + (n + 1)); n++; } while (n < count);
return printed;
}
console.log(ticketsWhile(0)); // []
console.log(ticketsDoWhile(0)); // [ 'T1' ]
console.log(ticketsDoWhile(-5)); // [ 'T1' ]
Asked for zero tickets, the while version checks 0 < 0, which is false, and prints nothing. The do...while version prints a ticket first and only then checks. Even a negative count still gets one ticket. When you test a loop, always try the case where it should do nothing.
Step 4: a job that must run once
do...while is the right tool when the body really must run at least once. Here is a function that halves an amount until it drops under a limit:
function halveUntilUnder(kobo, limit) {
let value = kobo;
let rounds = 0;
do {
value = Math.floor(value / 2);
rounds++;
} while (value > limit);
return { value, rounds };
}
console.log(halveUntilUnder(100000, 20000)); // { value: 12500, rounds: 3 }
100,000 becomes 50,000, then 25,000, then 12,500, which is under 20,000. Three rounds. Math.floor rounds down so the amount stays a whole number.
Step 5: the cost
Now pass an amount that is already under the limit:
function halveUntilUnder(kobo, limit) {
let value = kobo;
let rounds = 0;
do {
value = Math.floor(value / 2);
rounds++;
} while (value > limit);
return { value, rounds };
}
console.log(halveUntilUnder(5000, 20000)); // { value: 2500, rounds: 1 }
5,000 was already under 20,000, but it was halved anyway, because a do...while can't check first. If that isn't what you want, use while. Save do...while for jobs that truly need one turn first, such as showing a menu before reading the user's choice.
The full solution
The answer panel has both ticket functions and halveUntilUnder, and prints the zero-ticket results and the amount that was already under the limit. Its checks cover both loops with 3, 0 and -5 tickets, and both halving cases. Press Run to see the output.
function ticketsWhile(count) {
const printed = [];
let n = 0;
while (n < count) {
printed.push('T' + (n + 1));
n++;
}
return printed;
}
function ticketsDoWhile(count) {
const printed = [];
let n = 0;
do {
printed.push('T' + (n + 1));
n++;
} while (n < count);
return printed;
}
// Halve an amount until it is under a limit. The body has to run once, which is
// the case do...while is for -- and also the case where it bites.
function halveUntilUnder(kobo, limit) {
let value = kobo;
let rounds = 0;
do {
value = Math.floor(value / 2);
rounds++;
} while (value > limit);
return { value, rounds };
}
console.log('while, 0 tickets:', ticketsWhile(0));
console.log('do...while, 0 tickets:', ticketsDoWhile(0));
console.log('already under the limit:', halveUntilUnder(5000, 20000));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('both agree when there is work to do', ticketsWhile(3), ['T1', 'T2', 'T3']);
test('the do...while form gives the same three', ticketsDoWhile(3), ['T1', 'T2', 'T3']);
test('while checks first, so zero prints nothing', ticketsWhile(0), []);
test('do...while checks last, so zero still prints one', ticketsDoWhile(0), ['T1']);
test('and a negative count cannot save it either', ticketsDoWhile(-5), ['T1']);
test('halving down to a limit takes three rounds', halveUntilUnder(100000, 20000), { value: 12500, rounds: 3 });
test('an amount already under the limit is halved anyway', halveUntilUnder(5000, 20000), { value: 2500, rounds: 1 });
test('one round, not zero, because the guard runs after the body', halveUntilUnder(5000, 20000).rounds, 1);
The only difference between the two is where the condition sits, and it shows up in exactly one case: when the condition is false before the loop starts. while does nothing; do...while has already run the body once.
That is the whole trap in halveUntilUnder(5000, 20000). The amount was under the limit on arrival and got halved regardless, because a do...while cannot ask first. Reach for it only when the body genuinely must happen at least once — a menu prompt, a first read from a queue — and use while everywhere else. Note the semicolon after while (...): it closes a statement, and leaving it out is a syntax error rather than a silent bug, which is the one mercy here.
Common mistakes
- Using
do...whilewhen the body might need to run zero times. It always runs once, so an empty order still prints a ticket. - Putting the condition at the top by habit.
do (n < count) { ... }is not valid JavaScript. In ado...whileloop the condition always goes at the end, afterwhile. - Never changing what the condition checks. If
n++is missing,n < countstays true and the loop never ends, in either form.
Try it yourself
- Write
countdown(n)withwhilethat returns[n, n - 1, ..., 1], and check thatcountdown(0)returns[]. - Change
halveUntilUnderto usewhileso an amount already under the limit is left alone. - Write a
do...whileloop that rolls a dice withMath.floor(Math.random() * 6) + 1until it shows a 6, and counts the rolls.