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.
Syntax of a do…while Loop
The syntax of a do...while Loop in JavaScript is as follows:
do {
// code to be executed
}
while (condition);
- Condition: This is a Boolean expression that is checked after each iteration of the loop. If it evaluates to
true, the loop continues; if it evaluates tofalse, the loop ends.
Example of a do…while Loop
Here’s a simple example of a do...while Loop that prints the numbers from 1 to 5:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
In this example, i is initialized to 1, the console.log(i) inside the loop will print the number, and i is incremented by 1 at the end of each loop iteration. The condition checks if i is less than or equal to 5 after the loop has run once.
The do...while Loop is a unique tool in JavaScript, that allows you to ensure that a block of code is executed at least once before the condition is checked. It’s a fundamental concept that’s widely used in programming, so understanding how it works will greatly enhance your JavaScript coding skills.
