Member-only story
A do-while
loop in JavaScript is another type of loop statement that is similar to a while
loop, but with one key difference: the block of code inside the loop is executed at least once, regardless of whether the condition is true or false. Here's the basic syntax of a do-while
loop:
Not a Medium member? Read this article here
do {
// code to be executed
} while (condition);
- The
code to be executed
is the block of code that is executed at least once, and repeatedly executed as long as thecondition
is true. - The
condition
is evaluated after each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates.
Here’s an example of a do-while
loop that counts from 0 to 4:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
In this example, the variable i
is initialized outside of the loop, and the code inside the loop prints the value of i
to the console and increments i
by 1 after each iteration. The condition checks if i
is less than 5, and the loop will execute 5 times, with i
taking on the values of 0, 1, 2, 3, and 4, and each value of i
will be printed to the console.
You can also use a do-while
loop to iterate over an array: