Mark As Completed Discussion

Do-While Loops

In JavaScript, a do-while loop is similar to a while loop, with one key difference. The code block inside a do-while loop is executed at least once, regardless of the condition. Then, the condition is checked at the end of each iteration. If the condition is true, the loop will continue to execute. If the condition is false, the loop will terminate.

The basic syntax of a do-while loop in JavaScript is as follows:

JAVASCRIPT
1do {
2  // code to be executed
3} while (condition);

Here's an example that demonstrates the usage of a do-while loop:

JAVASCRIPT
1let x = 1;
2
3do {
4  console.log(x);
5  x++;
6} while (x <= 5);

In this example, the variable x is initialized with the value 1. The code block inside the do-while loop will be executed at least once, printing the value of x and incrementing its value by 1. The loop will continue to execute as long as x is less than or equal to 5.

Do-while loops are useful when you want to ensure that a certain code block is executed at least once before checking the condition. It can be particularly handy when you need to validate user input or perform an initial setup before entering a loop.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment