JavaScript do-while Loop with Example

javaScript do-while loop; Through this tutorial, i am going to teach you about javaScript do-while loop with examples.

JavaScript do-while Loop with Example

  • JavaScript do while Loop
  • Syntax of the do while Loop
  • Flowchart of do while loop
  • Example 1 – Print 1 to 10 numbers in javascript using do while loop
  • Example 2 – JavaScript do while loop with Break Statement

JavaScript do while Loop

The JavaScript  do-while  loop is also known as an exit control loop. The JavaScript do-while is test specified condition after executing a block of code. If the condition met false, at least once execute the block of code.

Syntax of the do while Loop

do{
   statement(s);
 } while(expression);

The do-while loop always executes the block of code least once before it check specified condition.

Because the condition is checked only after the block of code executes once. The do-while loop is called a post-test/exit control loop.

You have known above, the do while loop is known as an exit control loop. For this reason, it is possible that the block of code inside the do while loop is executed at least once, if the specified condition met false.

Flowchart of do while loop

Example 1 – Print 1 to 10 numbers in javascript using do while loop

See the following example of the do-while loop.

<script>
let count = 0;
do {
    count++;
    document.write(count + "<br>")
} while (count < 10);
</script>

The output of the script shown below:

1
2
3
4
5
6
7
8
9
10

Explanation of above given example:

  • First, define count variable and assign value to it.
  • Next, the do while loop checks specified condition after execute block of code, if count is less than 10 and execute the statements inside the loop body.
  • Next, in each do while loop iteration, increments count by 1.And After 10 iterations, the condition count < 10 met false and loop will be terminate.

Example 2 – JavaScript do while loop with Break Statement

See the following example of the do-while loop.

<script>
    let count = 0;
    do {
    
        if(count == 5)
        break;
        count++;
        document.write(count + "<br>")
    } while (count < 10);
</script>

The output of the script shown below:

1
2
3
4
5

Explanation of above given example:

  • First, define count variable and assign value to it.
  • Next, the do while loop checks specified condition after executing block of code, if count is less than 10 and execute the statements inside the loop body.
  • Next, in each do while loop iteration, increments count by 1. Using a break statement, stop the execution of loop After 5 iterations.

Conclusion

In this tutorial, you have learned what is do-while  loop and how to use the do-while loop.

Recommended JavaScript Tutorial

Be First to Comment

Leave a Reply

Your email address will not be published.