'do while' Loop
What is a 'do while' Loop?
In JavaScript, the 'do while' loop is similar to the 'while' loop but with one key difference. The 'do while' loop executes a block of code once, and then continues to execute the code as long as a specified condition is true. The key difference is that the code block is always executed at least once, regardless of whether the condition is true or false.
There are mainly two types of loops.
- Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loops are entry-controlled loops.
- Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
The syntax for a 'do while' loop in JavaScript is as follows:
do {
// code to be executed
} while (condition);
Here's an example to illustrate how a 'do while' loop works:
let i = 0;do {
console.log(i);
i++;
} while (i < 5);
In this example, the code will output the values of `i` from 0 to 4. Even though the condition `i < 5` becomes false after the first iteration, the code block is still executed once.
Comparison between the while and the do-while loop
The do-while loop executes the content of the loop once before checking the condition of the while loop. While the while loop will check the condition first before executing the content.
While Loop
- It is an entry condition looping structure.
- The number of iterations depends on the condition mentioned in the while block.
- The block control condition is available at the starting point of the loop.
- The block of code is controlled at starting.
Do-While Loop
- It is an exit condition looping structure.
- The number of iterations will be at least one irrespective of the condition.
- The block control condition is available at the endpoint of the loop.
- The block code is controlled at the end.
Key Takeaways
- The 'do while' loop is similar to the 'while' loop, but with the key difference that the code block is always executed at least once.
- The syntax for a 'do while' loop is `do { // code } while (condition);`.
- Use a 'do while' loop when you need to execute a piece of code at least once, and then continue executing it based on a condition.
Comments
Post a Comment