Do...While Loop
The do...while
loop is used to execute a block of code repeatedly as long as a specified condition is true
. It is a type of exit-controlled loop, which means the condition is checked after the block of code is executed.
The do...while
loop syntax is similar to the while
loop, but the condition is checked at the end of the loop body. Also, unlike the while loop, the do...while
loop will always execute the code block at least once, regardless of the condition.
Here is the syntax of the do...while
loop:
do {
// Code block to be executed
} while (condition);
- The code block inside the
do
loop is executed at least once before the condition is checked. - The
condition
is evaluated after each iteration. If the condition istrue
, the code block inside the loop is executed again; otherwise, the loop terminates. - The code block inside the
do
loop will continue to execute until the condition evaluates tofalse
. - If the condition is
false
from the beginning, the code block inside the loop will execute at least once.
Example
Here is an example of using a do...while
loop to print numbers from 1
to 5
:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
In the example above, the do...while
loop prints the value of i
and increments i
by 1
after each iteration. The loop continues to execute as long as the value of i
is less than or equal to 5
.
A better way to understand the difference between the do...while
loop and the while
loop is to compare the following code snippets:
let i = 9;
while (i <= 5) {
console.log(i);
i++;
}
let i = 0;
do {
console.log(i);
i++;
} while (i <= 5);
In the while
loop, the condition i <= 5
is false
from the beginning, so the code block inside the loop will not execute at all. However, in the do...while
loop, the code block will execute at least once before the condition is checked.
Nested Do...While Loop
You can nest do...while
loops inside each other to create complex patterns or iterate over multi-dimensional arrays. When you nest loops, the inner loop is executed multiple times for each iteration of the outer loop.
Here is an example of using nested do...while
loops to create a multiplication table:
let i = 1;
do {
let j = 1;
do {
console.log(`${i} * ${j} = ${i * j}`);
j++;
} while (j <= 10);
i++;
} while (i <= 10);
In the example above, the outer do...while
loop iterates over the numbers from 1
to 10
. For each iteration of the outer loop, the inner do...while
loop iterates over the numbers from 1
to 10
and prints the multiplication table for the current number.
That's it! You now know how to use the do...while
loop in JavaScript to execute a block of code repeatedly based on a specified condition. Happy coding! 🚀
In the next section, we will learn about the for..in
loop in JavaScript. Let's keep going! 🚀
Made with ❤️ by Fasakin Henry