Emmanuel Akinfulubi

JavaScriptBasic

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:

  1. Check the condition. If it is false, stop.
  2. Run the body.
  3. Go back to 1.

A do...while loop:

  1. Run the body.
  2. Check the condition. If it is false, stop.
  3. 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

JavaScript

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

easy

Write 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. 1. A while loop can run its body zero times; a do...while cannot.
  2. 2. Write the count of zero down as a test case, because that is where the two differ.
  3. 3. do { } while (cond); keeps its semicolon at the end.

Step 1: print tickets with while

Step 1

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

Step 2

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:

Step 3

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:

Step 4

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:

JavaScript

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.

The answer

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.

8 checks

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...while when 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 a do...while loop the condition always goes at the end, after while.
  • Never changing what the condition checks. If n++ is missing, n < count stays true and the loop never ends, in either form.

Try it yourself

  1. Write countdown(n) with while that returns [n, n - 1, ..., 1], and check that countdown(0) returns [].
  2. Change halveUntilUnder to use while so an amount already under the limit is left alone.
  3. Write a do...while loop that rolls a dice with Math.floor(Math.random() * 6) + 1 until it shows a 6, and counts the rolls.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.