Open In App

JavaScript do…while Loop

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.

Syntax:



do {
// Statements
}
while(conditions)

Example 1: In this example, we will illustrate the use of a do…while loop




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




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 exit-controlled loop It is an entry-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:

We prefer you to check this article to know more about JavaScript Loop Statements.


Article Tags :