Do While Loop
Learn how to use the do while loop in JavaScript to run code at least once before checking a condition.
What is a Do While Loop?Link to this section
A do while loop is a control flow statement that executes a block of code once, and then repeats the execution as long as a specified condition evaluates to true. Unlike standard loops, it guarantees that the code inside the block runs at least once because the condition is checked at the very end.
This loop prints numbers from 1 to 3 by incrementing the count variable on each iteration.
- `do` is the **keyword** that begins the block of code to execute.
- `{ console.log(count); }` is the **code block** that runs on every iteration.
- `while` is the **keyword** that signals the end of the block and checks the condition.
- `(count <= 3)` is the **condition** that determines whether the loop should run again.
It is used when you need a piece of code to execute at least once regardless of the initial condition state.
Why Do We Need Do While Loops?Link to this section
Do while loops are essential for scenarios where an action must happen first before a decision can be made to continue.
- Prompting a user for input at least once until they enter a valid value.
- Displaying a menu of options to a customer before asking for their choice.
- Attempting a network connection at least once before evaluating retry logic.
- Running a game loop for a single turn before checking if the player wants to quit.
- Rolling dice in a game simulator at least once before checking score thresholds.
- Reading a file chunk at least once before checking if the end of the file is reached.
Even if the limit was restricted, the action executes at least once.
This example shows how an operation runs first and then verifies if another iteration is necessary.
About Do While LoopsLink to this section
The do while loop is part of the JavaScript loop family, sitting alongside for and while loops. The main difference lies in the order of execution: the body runs first, and the condition is evaluated second. Semicolons are required after the while condition parentheses at the end of the statement, unlike other loop structures.
| Loop Type | Condition Check | Minimum Runs |
|---|---|---|
| for loop | Before iteration | 0 |
| while loop | Before iteration | 0 |
| do while loop | After iteration | 1 |
The number 10 prints out once because the condition is checked only after the first run.
Variations and Mechanics of Do While LoopsLink to this section
1. Standard Do While LoopLink to this section
The standard form executes the code block once and continues looping if the condition remains true.
Counts down from 5 to 3.
tip
2. Do While Loop with User Input SimulationLink to this section
A common use case in backend or console applications is validating input where you must ask the user at least once.
Simulates retrying until a condition succeeds.
note
3. Infinite Do While LoopLink to this section
If the condition never evaluates to false, the loop will run forever and can crash your application or freeze the browser thread.
Using false as the condition ensures it only runs once safely.
warning
Comparison with While LoopsLink to this section
Choosing between a while loop and a do while loop depends entirely on whether your code needs to execute at least once before checking the condition.
Demonstrates the distinct execution guarantee of the do while loop.
note
Using Break and ContinueLink to this section
You can control the flow inside a do while loop using break to exit early or continue to skip the rest of the current iteration.
Skips printing the number 2.
tip
Complete Coding ExampleLink to this section
Calculates how many months it takes to reach a savings target of 300 with monthly additions of 50.
This complete example shows a do while loop calculating savings over time, ensuring at least one deposit calculation occurs.
Important NotesLink to this section
- The do while loop guarantees at least one execution of the code block.
- The condition is checked at the end of the loop, after the code block runs.
- A semicolon is required after the while condition parentheses.
- Always update loop control variables inside the block to avoid infinite loops.
- Infinite loops freeze your application or browser tab.
- The break statement immediately terminates the loop.
- The continue statement skips the remainder of the current iteration.
- Do while loops are ideal for user prompt validation and retry mechanisms.
- They differ from while loops because while checks the condition first.
- Scope rules inside the loop follow standard block scope guidelines.
SummaryLink to this section
You have learned how the do while loop operates by executing code first and checking conditions second. This structure guarantees at least one run, making it powerful for user inputs, validations, and iterative game mechanics. With this knowledge, you can build more robust control flows in your JavaScript applications.
Check Your UnderstandingLink to this section
What is the minimum number of times a do while loop's code block will execute?
Practice ChallengesLink to this section
1. At Least Once
Write a do while loop that prints "Running!" once, even though the condition is false immediately.
Expected output
Running!Hint: Set your condition to false inside the while statement.
2. Countdown Timer
Create a do while loop that counts down from 3 to 1 and logs each number.
Expected output
3
2
1Hint: Decrement your counter variable inside the block.
3. Inventory Restock Simulator
An item has 5 units in stock. Use a do while loop to sell 1 unit at a time until stock reaches 0, logging each sale.
Expected output
Sold 1 unit, remaining: 4
Sold 1 unit, remaining: 3
Sold 1 unit, remaining: 2
Sold 1 unit, remaining: 1
Sold 1 unit, remaining: 0Hint: Subtract 1 from stock inside the loop and check stock > 0.
4. Password Retry Simulation
Simulate a user guessing a PIN. Start with 3 attempts and decrement until 0, logging each attempt.
Expected output
Attempt 3
Attempt 2
Attempt 1Hint: Use a decrementing counter inside the do block.
5. Double Until Threshold
Start with a score of 2. Use a do while loop to double the score until it is greater than or equal to 20, logging each step.
Expected output
4
8
16
32Hint: Multiply the score by 2 on each iteration.
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion