Skip to main content

JavaScript do-while Loop (Live Playground)

In this tutorial, we will explore the do-while loop, and learn how to use it in our code to help perform repetitive tasks.

do-while Loop

A do-while loop is similar to a while loop, with the main difference being that the block of code is executed at least once before checking the condition.

Example:

let i = 0;

do {
console.log(`Iteration ${i + 1}`);
i++;
} while (i < 5);

In the example above, the loop will run as long as i is less than 5, and the output will display the iteration number from 1 to 5. Even if the condition is false initially, the loop will still execute once.

Live Playground, Try it Yourself

Conclusion

Understanding and using the do-while loop is essential for performing repetitive tasks in your JavaScript programs.