A do… while loop in JavaScript is a control statement in which the code is allowed to execute continuously based on a given boolean condition. It is like a repeating if statement.
The do…while loop can be used to execute a specific block of code at least once
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.
Syntax:
do { // Statements } while(conditions)
Example 1: In this example, we will illustrate the use of a do…while loop
Javascript
let test = 1; do { console.log(test); test++; } while (test<=5) |
Output:
1 2 3 4 5
The main difference between do…while and while loop is that it is guaranteed that do…while loop will run at least once. Whereas, the while loop will not run even once if the given condition is not satisfied
Example 2: In this example, we will try to understand the difference between the two loops
Javascript
let test = 1; do { console.log(test); } while (test<1) while (test<1){ console.log(test); } |
Output:
1
Explanation: We can see that even if the condition is not satisfied in the do…while loop the code still runs once, but in the case of while loop, first the condition is checked before entering into the loop. Since the condition does not match therefore the while loop is not executed.
Let us compare the while and do…while loop
do…while | while |
---|---|
It is an entry-controlled loop | It is an exit-controlled loop |
The number of iterations will be at least one irrespective of the condition | The number of iterations depends upon the condition specified |
The block code is controlled at the end | The block of code is controlled at starting |
Note: When we are writing conditions for the loop we should always add a code that terminates the code execution otherwise the loop will always be true and the browser will crash.
Supported Browser:
- Chrome
- Edge
- Safari
- Firefox
- Internet Explorer
We prefer you to check this article to know more about JavaScript Loop Statements.