Menu
Coddy logo textTech

Do While Loop

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 43 of 77.

The do...while loop is similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop will always run the code once, and then it will check if it should continue.

Here's the syntax of a do...while loop:

do {
    code;
} while (condition);

The code inside the do block is executed first.

Then, the condition inside the while is evaluated. If the condition is true, the loop continues to the next iteration. If the condition is false, the loop stops.

Let's look at an example:

let count = 0;
do {
    console.log(count);
    count++;
} while (count < 5);

This code will output:

0
1
2
3
4

Even if the initial value of count is greater than or equal to 5, the code inside the do block will still be executed once.

For example:

let count = 6;
do {
    console.log(count);
    count++;
} while (count < 5);

This code will output:

6

Use cases for do...while loops are less common than for or while loops, but they can be useful in situations where you need to ensure that a block of code is executed at least once, regardless of the condition.

challenge icon

Challenge

Beginner

Write a do...while loop that starts with a variable count set to 5. The loop should:

  1. Print the current value of count.
  2. Decrease count by 1 after each iteration.
  3. As long as count is bigger than 0

Cheat sheet

The do...while loop executes code at least once before checking the condition:

do {
    code;
} while (condition);

The code inside the do block runs first, then the condition is evaluated. If true, the loop continues; if false, it stops.

let count = 0;
do {
    console.log(count);
    count++;
} while (count < 5);

Even if the condition is initially false, the code executes once:

let count = 6;
do {
    console.log(count);
    count++;
} while (count < 5);
// Output: 6

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals