Hello! In our last lesson, we mastered the for loop, which is your go-to tool when you know exactly how many times you need to repeat a piece of code. We learned how its three-part structure—initialization, condition, and final expression—gives you precise control over the number of iterations.
But what happens when you don't know how many times a loop should run? Imagine a game where you have to guess a number. The game should keep asking for your guess until you get it right. You might guess it on the first try or the tenth. This is where condition-based loops come in.
Today, we'll explore the while and do...while loops. These loops don't depend on a counter; they depend on a condition being true. By the end of this lesson, you will be able to use these powerful loops to handle situations where the number of repetitions is unknown.
The while Loop: "Keep Going as Long as This is True"
The while loop is conceptually the simplest loop. Its structure is:
while (condition) {
// code to execute as long as the condition is true
}
It works like this:
- JavaScript checks the
conditionin the parentheses. - If the condition is
true, the code block inside the{}is executed. - After the block finishes, it goes back to step 1 and checks the condition again.
- This cycle continues until the condition becomes
false, at which point the loop terminates.
Let's watch a short video that breaks down the while loop and compares its components to the for loop you already know.
#26 While/do while loop | JavaScript Full Tutorial
The video "#26 While/do while loop" by Dev Dreamer clearly explains the structure of a while loop, showing how the initializer, condition, and final expression work together.
Watch from 00:33 to 03:18. Pay close attention to where the three key parts of the loop (initializer, condition, final expression) are placed in relation to the while statement.
As the video explained, the for loop's three parts are still present, but they are arranged differently:
- Initializer: A variable is declared and initialized before the loop starts.
- Condition: This is the only part that goes inside the
whileparentheses(). - Final Expression (Update): This happens inside the loop's body, usually as the last line.
Here's a simple example that counts from 1 to 5:
// 1. Initializer
let i = 1;
// 2. Condition
while (i <= 5) {
console.log('The number is: ' + i);
// 3. Update
i++;
}
Visualizing the while Loop Flow
To help you internalize this process, let's look at a flowchart. This visual model shows exactly how JavaScript decides whether to run the loop's body or exit.

The Danger of Infinite Loops
What would happen in our example if we forgot the i++; line?
The variable i would start at 1. The condition 1 <= 5 would be true, so the loop would run. Then, it would check the condition again. Since i is still 1, the condition 1 <= 5 is still true. This would repeat forever, creating an infinite loop that can crash your browser or program.
Crucial takeaway: With while loops, you are responsible for ensuring that something inside the loop body eventually makes the condition false.
Test your understanding!
What will be the output of the following code? Trace the value of count in your head.
let count = 10;
while (count > 7) {
console.log(count);
count = count - 1;
}
Show answer
The output will be:
10
9
8
Explanation:
countstarts at10.10 > 7is true, so10is printed.countbecomes9.9 > 7is true, so9is printed.countbecomes8.8 > 7is true, so8is printed.countbecomes7.7 > 7is false, so the loop stops.
The do...while Loop: "Run at Least Once"
Now, let's look at a variation: the do...while loop. It's very similar to while, but with one fundamental difference: the code block is executed at least once, before the condition is checked for the first time.
The syntax is:
do {
// code to execute
} while (condition);
Notice the while (condition); is at the end. The program will "do" the code in the block, and then check the condition to see if it should do it again.
Let's look at a flowchart to see this different execution order.

To see a practical explanation of this, let's continue the video from before.
#26 While/do while loop | JavaScript Full Tutorial
The Dev Dreamer video now introduces the do...while loop and highlights its unique behavior.
Watch the segment from 05:30 to 07:45. Focus on the explanation of why the do...while loop always runs at least once.
When is do...while useful?
This loop is perfect for situations where you need to perform an action first and then decide if you want to repeat it. A classic example is prompting a user for input. You need to ask for the input at least once.
Consider this code that asks a user to enter a number greater than 100.
The article "Loops: while and for" from the javascript.info website provides a perfect, real-world scenario for using a do...while loop.
Scroll down to the task titled "Repeat until the input is correct" and read its description and solution. This demonstrates a case where the loop body must execute before the condition can even be checked.
In that example, the program must prompt the user first to get a value for num. Only then can it check the condition num <= 100. A regular while loop wouldn't work as cleanly because num wouldn't have a value to check on the first pass.
Test your understanding!
Let's compare while and do...while directly. What will be the output of these two separate code blocks?
Block 1:
let x = 10;
while (x < 10) {
console.log("while loop executed");
x++;
}
Block 2:
let y = 10;
do {
console.log("do...while loop executed");
y++;
} while (y < 10);
Show answer
Block 1 Output:
Nothing will be printed to the console.
Explanation: The condition x < 10 is immediately false (since 10 is not less than 10), so the loop's body never runs.
Block 2 Output:
do...while loop executed
Explanation: The do block runs once before the condition is checked. It prints the message. Then, y becomes 11. The condition y < 10 (11 < 10) is checked and found to be false, so the loop stops.
Deciding Which Loop to Use
You now know three types of loops: for, while, and do...while. How do you choose? Here's a simple guide:
-
Use a
forloop when you know the number of iterations ahead of time.- Example: "Iterate through the 12 months of the year" or "Loop 10 times."
-
Use a
whileloop when the number of iterations is unknown and depends on a condition that should be checked before the loop runs.- Example: "Keep fetching data chunks from a server as long as there is more data to fetch." (You might get zero chunks if there's no data).
-
Use a
do...whileloop when the number of iterations is unknown, but you need the loop to run at least once.- Example: "Ask the user for a password, and if it's wrong, ask again." (You must ask the first time).
The following video segment provides a great summary of this decision-making process.
#26 While/do while loop | JavaScript Full Tutorial
Let's listen to a final clip that summarizes the rule of thumb for choosing between for and while loops.
Watch from 07:45 to 09:10. This gives clear examples of when you would choose one loop over another.
Conclusion
You've now added two more essential tools to your programming toolkit. While for loops are about counting, while and do...while loops are about continuing as long as a condition holds. This opens up a new world of possibilities for writing dynamic and responsive programs.
Key Takeaways:
whileloops are for condition-based iteration. The condition is checked before the loop body runs.do...whileloops are similar, but the loop body is guaranteed to run at least once before the condition is ever checked.- These loops are ideal when the number of iterations is unknown.
- It is your responsibility to ensure the condition will eventually become
falseto prevent infinite loops.
Next Up:
We've seen that loops repeat a block of code. But what if, in the middle of an iteration, we want to stop the entire loop? Or what if we just want to skip the rest of the current iteration and move to the next one? In the next lesson, we'll learn about the break and continue statements, which give us even finer-grained control over our loops' execution.