do-while Loop

After for loop and while loop in JavaScript , another most common loop used is do-while loop in JavaScript. The do-while loop in JavaScript is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition becomes true. Unlike other loops, the do-while loop guarantees the execution of a block of code at least once before checking the condition. It prints the statement at least once and then checks the condition.

The syntax of do-while loop in JavaScript is:

do{
    //code
} while(condition);

Here's how the do-while loop works:

  1. The code block inside the do statement is executed first, without checking any conditions.
  2. After executing the code block, the condition in the while statement is evaluated.
  3. If the condition evaluates to true, the code block is executed again. The loop continues until the condition becomes false.
  4. If the condition initially evaluates to false, the code block is still executed once before exiting the loop.

Example 1:

let i=0;
do{
    console.log(i);
    i++:
} while(i<5);
Output 1:

0

1

2

3

4

Inference 1 : even if i which is 0 is not greater than 5 as per the given condition, do-while loop still executes the statement at least once and then checks the condition by incrementing the value.

Example 2:

let count = 1;
do {
    console.log('Count:', count);
    count++;
} while (count <= 5);
Output 2:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

Conclusion

To summarize, the do-while loop in JavaScript executes a block of code at least once, regardless of the condition. It is useful when you need to repeat a task until a specific condition is met. By understanding its syntax and usage, you can leverage the power of do-while loops in your JavaScript programs.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs