JavaScript while and do…while Loops Get Certified
In addition to the for loop, JavaScript provides two
other looping structures: the while loop and the
do...while loop. Both repeat a block of code as long
as a condition remains true.
The main difference between them is when the condition
is checked: before each iteration for while, or
after each iteration for do...while.
In this lesson, you will learn the syntax of both loops, when to use each one, and how to avoid some common pitfalls.
The while Loop
A while loop checks its condition before running the
loop body. If the condition is false from the start,
the loop body never runs at all.
What this code does: A while loop checks the condition before each iteration.
As long as count <= 5, it prints the number and increases count. Output: 1 through 5.
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
let count = 1; creates a variable named count and sets it to 1. Unlike a for loop, a while loop has no place in its header to create a counter, so you declare it before the loop.while (count <= 5) { starts the loop. The condition in the parentheses is checked before every pass. While count <= 5 is true, the body runs; the first time it is false, the loop ends. At the start 1 <= 5 is true, so the body runs.console.log(count); prints the current value of count. On the first pass it prints 1.count++; adds 1 to count. This line is essential: a while loop has no built-in update, so you must change the variable inside the body. Without it, count would stay 1 and the loop would never end.} ends the body, and JavaScript jumps back to line 2 to check the condition again. After the pass that prints 5, count becomes 6, 6 <= 5 is false and the loop stops. The output is 1, 2, 3, 4, 5.
This loop prints the numbers 1 through 5, stopping once
count becomes greater than 5.
A while Loop That Never Runs
Because the condition is checked first, the loop body may run zero times.
What this code does: Because count starts at 10, the condition count <= 5
is already false, so the loop body never runs. Only the message after the loop is printed.
let count = 10;
while (count <= 5) {
console.log(count);
count++;
}
console.log("Loop finished. Count is:", count);
let count = 10; sets count to 10, which is already larger than the limit of 5 used in the condition below.while (count <= 5) { checks the condition before running the body. 10 <= 5 is false, so JavaScript skips the whole loop body and continues after the closing brace.count, but the body never runs, so nothing is printed from here.count. It never runs, so count stays at 10.} ends the loop body. The body ran zero times, which is the key feature of a while loop.count. Since the loop never changed it, the output is Loop finished. Count is: 10. This is the only output of the program.
Since count starts at 10, the condition
count <= 5 is false right away, so
the loop body never executes.
The do…while Loop
A do...while loop runs the loop body first, and only
checks the condition afterward. This guarantees the loop body
runs at least once, no matter what.
What this code does: A do...while loop runs the body first, then checks the condition.
It still counts from 1 to 5, but the structure guarantees at least one run even if the condition starts false.
let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);
let count = 1; creates the counter and sets it to 1, exactly as in the while version.do { opens the loop body. Unlike while, there is no condition here. JavaScript runs the body first and only checks the condition at the end.console.log(count); prints the current value. On the first pass it prints 1.count++; adds 1 to count. As in a while loop, you must update the variable yourself so the condition can eventually become false.} while (count <= 5); closes the body and now checks the condition. If it is true, JavaScript jumps back up to do { and runs the body again. When count becomes 6 the condition is false and the loop ends. Note the semicolon at the end: it is required in a do...while loop. The output is 1 to 5, one number per line.
Notice the semicolon after while (count <= 5).
This is required syntax for a do...while loop.
do…while Always Runs at Least Once
Unlike while, a do...while loop runs
its body once even if the condition is false from
the very beginning.
What this code does: Here count starts at 10, so a normal while would skip the body.
With do...while, the body runs once, prints the message, then the condition fails and the loop stops.
let count = 10;
do {
console.log("This runs at least once. Count is:", count);
count++;
} while (count <= 5);
let count = 10; sets count to 10. The condition at the bottom (count <= 5) is already false for this value.do { begins the body. JavaScript enters it without checking any condition, so the body is guaranteed to run once.count. The output is This runs at least once. Count is: 10.count++; increases count from 10 to 11.} while (count <= 5); checks the condition for the first time, after the body already ran. 11 <= 5 is false, so the loop ends. A normal while loop would have printed nothing at all for this starting value.
Even though count starts at 10 and the
condition is immediately false, the console still
prints the message once before the loop exits.
while vs. do…while
| Aspect | while | do…while |
|---|---|---|
| Condition checked | Before the loop body runs | After the loop body runs |
| Minimum number of runs | 0 (may never run) | 1 (always runs at least once) |
| Requires trailing semicolon | No | Yes |
break and continue
Just like the for loop, both while and
do...while loops support break (to stop
the loop entirely) and continue (to skip to the next
iteration).
What this code does: Inside a while loop, continue skips even numbers
and break stops the loop when i goes above 7. Only the odd numbers 1, 3, 5, 7 are printed.
let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) {
continue;
}
if (i > 7) {
break;
}
console.log(i);
}
let i = 0; creates the counter i and sets it to 0.while (i < 10) { keeps the loop running while i is less than 10. The break statement further down will stop it earlier.i++; increases i at the top of the body, so the first pass works with i equal to 1. Putting the update before continue is important: if it were placed after continue, the update would be skipped for even numbers and the loop would get stuck.if (i % 2 === 0) { uses the remainder operator %. i % 2 is 0 for even numbers, so this condition is true for 2, 4, 6 and 8.continue; ends the current pass immediately and jumps back to the while condition on line 2. The lines below (the break check and console.log) are skipped for even numbers.} closes the if block that began on line 4.if (i > 7) { is only reached by odd numbers, because even numbers were skipped. For 1, 3, 5 and 7 it is false. For 9 it is true.break; ends the whole while loop immediately, even though i < 10 is still true. This happens when i is 9. (When i is 8, continue runs first, because 8 is even.)} closes the if block that began on line 7.console.log(i); is only reached by odd numbers that are 7 or less, so it prints 1, 3, 5 and 7.} ends the loop body and returns to the condition. Tracing the passes: 1, 3, 5 and 7 are printed, 2, 4, 6 and 8 are skipped by continue, and 9 triggers break. The output is 1, 3, 5, 7.
This loop skips even numbers with continue, and
stops entirely with break once i
exceeds 7.
Avoiding Infinite Loops
Unlike a for loop, a while or
do...while loop does not have a built-in update
expression. It’s your responsibility to make sure something
inside the loop eventually makes the condition false.
What this code does: An infinite-loop example is shown commented out so it cannot freeze the page.
Forgetting to update the loop variable (e.g. missing count++) means the condition never becomes false.
// Be careful! This is an example of an infinite loop.
// let count = 1;
// while (count <= 5) {
// console.log(count);
// // Missing count++ here means the condition never becomes false.
// }
console.log("Always update your loop variable inside the loop body.");
// is a comment that JavaScript ignores. This one warns that the code below is an example of an infinite loop, which is why all of it is commented out.count and set it to 1. It is commented out so that the example cannot run.while loop that runs while count <= 5. Because nothing inside the loop ever changes count, the condition would stay true forever.1 over and over again, endlessly.count++ is missing. Without an update inside the body, the condition never becomes false.// marks and run this in the editor, as it would freeze the browser tab.Always update your loop variable inside the loop body.Looping Until a Condition Is Met
while loops are especially useful when you don’t
know in advance exactly how many times a loop needs to run, such
as when processing data until some condition changes.
What this code does: A practical while loop: keep withdrawing 200 while the balance
is at least 200. After the loop we print how many withdrawals were made and the remaining balance.
let balance = 1000;
let withdrawalCount = 0;
while (balance >= 200) {
balance -= 200;
withdrawalCount++;
}
console.log("Withdrawals made:", withdrawalCount);
console.log("Remaining balance:", balance);
let balance = 1000; stores the starting amount of money, 1000.let withdrawalCount = 0; will count how many withdrawals are made. It starts at 0.while (balance >= 200) { checks before every pass whether the balance is at least 200. We do not know in advance how many passes that will be, which makes a while loop a good choice.balance -= 200; is shorthand for balance = balance - 200;. It reduces the balance by 200. This is the line that eventually makes the condition false.withdrawalCount++; adds 1 to the number of withdrawals made.} ends the body. The balance goes 1000, 800, 600, 400, 200, 0 as five withdrawals are made. When it is 0, 0 >= 200 is false and the loop ends.Withdrawals made: 5.Remaining balance: 0. Try changing the starting balance to 1050 and see the remainder of 50 left over.
Here, we don’t know in advance how many withdrawals will fit
within the balance, so a while loop is a natural
fit.
Practical Example: do…while
A do...while loop is a good fit when you need to
perform an action at least once before checking whether to repeat
it, such as validating input.
What this code does: A do...while is a natural fit for “try at least once” logic,
such as password attempts. It tries each code until the correct one is found or attempts run out.
let attempts = 0;
const correctCode = "1234";
const enteredCodes = ["0000", "1111", "1234"];
let accessGranted = false;
do {
const entered = enteredCodes[attempts];
console.log("Attempt " + (attempts + 1) + ": trying " + entered);
if (entered === correctCode) {
accessGranted = true;
}
attempts++;
} while (!accessGranted && attempts < enteredCodes.length);
console.log("Access granted:", accessGranted);
console.log("Total attempts:", attempts);
let attempts = 0; counts how many codes have been tried. It also doubles as the index into the array of codes below, so it starts at 0.const correctCode = "1234"; stores the code that grants access. It is a constant because it never changes.const enteredCodes = ["0000", "1111", "1234"]; is an array that simulates three codes a user typed in, in order. The correct code is last.let accessGranted = false; is a flag that starts as false and is set to true when the correct code is found.do { opens the body. A do...while is the right choice here because at least one attempt must always be made before deciding whether to try again.const entered = enteredCodes[attempts]; reads the code at position attempts in the array. On the first pass it is "0000", then "1111", then "1234". Because it is declared with const inside the body, a fresh variable is created on each pass.+. (attempts + 1) is in parentheses so the numbers are added before joining the text, giving a human-friendly number starting at 1. The output is Attempt 1: trying 0000, Attempt 2: trying 1111 and Attempt 3: trying 1234.if (entered === correctCode) { checks whether the code that was tried matches. It is true only on the third attempt.accessGranted = true; sets the flag when the correct code is found.} closes the if block that began on line 8.attempts++; adds 1 to the attempts counter. This also moves to the next code in the array for the next pass.} while (!accessGranted && attempts < enteredCodes.length); decides whether to run the body again. It repeats only while both parts are true: !accessGranted (access has not been granted yet; ! means NOT) and attempts < enteredCodes.length (there are still codes left to try). After attempt 3, accessGranted is true, so !accessGranted is false and the loop ends. The length check also prevents reading past the end of the array.Access granted: true.Total attempts: 3. Try removing "1234" from the array: the loop would end after the codes run out, with access denied.Common Mistakes With while and do…while
- Forgetting to update the loop variable inside the loop body, causing an infinite loop.
- Forgetting the semicolon after the
while (...)condition in ado...whileloop. - Assuming a
whileloop always runs at least once, when it might not run at all if the condition startsfalse. - Using a
whileloop when aforloop would be clearer, especially when the number of iterations is already known. - Placing the update expression before a
continuestatement incorrectly, which can accidentally skip it and cause an infinite loop.
Best Practices for while and do…while
- Use
whilewhen the number of iterations isn’t known in advance and depends on a changing condition. - Use
do...whilewhen the loop body must run at least once regardless of the condition. - Always ensure the loop variable is updated somewhere inside the loop body.
- Prefer a
forloop when you already know exactly how many times to iterate. - Keep the condition simple and easy to reason about at a glance.
Quick Summary
- A
whileloop checks its condition before each iteration and may never run. - A
do...whileloop checks its condition after each iteration and always runs at least once. - Both loops support
breakandcontinue. - Neither loop has a built-in update expression, so you must update the loop variable manually inside the loop body.
whileis a good fit when the number of iterations isn’t known ahead of time.do...whileis useful when an action must happen at least once before checking a condition.
Try It Yourself
Modify the code below. Try changing the starting value of
count to something greater than 5 and
compare how the while and do...while
versions behave differently.
What this code does: Practice comparison: with count = 6, the while
loop never runs, but the do...while runs once. Change the starting value and click
Test My Code to explore the difference.
let count = 6;
console.log("--- while loop ---");
while (count <= 5) {
console.log(count);
count++;
}
console.log("--- do...while loop ---");
count = 6;
do {
console.log(count);
count++;
} while (count <= 5);
let count = 6; sets the starting value to 6, which is greater than the limit of 5. Change this number (for example to 3) and run the code again to see how both loops behave.--- while loop --- so that you can tell the two outputs apart.while (count <= 5) { checks the condition first. 6 <= 5 is false, so the body is skipped.count, but it never runs here.count, but it never runs here.} of the while loop. It printed nothing for this starting value.--- do...while loop ---.count = 6; sets count back to 6. There is no let this time, because the variable already exists. Without the reset, count would still hold the value left by the first loop.do { opens the body of the second loop. It will run without checking a condition first.6. This is the proof that a do...while loop always runs at least once.count++; increases count to 7.} while (count <= 5); checks the condition after the body has run. 7 <= 5 is false, so the loop ends. The full output is --- while loop ---, --- do...while loop --- and 6.Tip: If you ever need code to run at least once no matter what — like showing a menu before checking whether the user wants to continue — reach fordo...whileinstead of adding an extra copy of the code before a regularwhileloop.
Understanding while and do...while
loops is essential before moving on to functions, arrays, and
more advanced JavaScript concepts.
🧪 Test Your JavaScript Code
Edit the code on the left and click “Run Code” to see the console output on the right.
Click “Run Code” to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.