do-while Loop In JavaScript

avatar

image.png

Image Source

We have another type of iterative control statement in JavaScript which is do while loop and it is somewhat similar to while loop. The only difference between these two is that in while loop the condition is checked first and the statement gets executed only if the condition evaluates to true. In the case of do while loop, the iteration is performed firstly and only after that the condition is checked. This will go and continue on until the condition becomes false. In the world of programming, we rarely utilize do while loop in making software and most of the times while loop is preferred over them. Even if the condition is false, the loop gets executed once since the condition is at the end of loop. The basic syntax of do-while loop is:

do
{
 //code statement
}
while (condition)

Lets see a simple code where we will write a condition that is false and you can see the statement inside loop gets executed once.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript While Loop</title>
<script>
    var x=4;
    do{
        document.write("<h3>Just checking false do-while loop condition.</h3>");
        x=x-1;
    }
    while(x<1)
</script>
</head>
<body>
</body>
</html>

Here we have initialized the value of x to 4 and we are writing a loop that prints a simple statement. The condition (4<1) is false and you can see the statement being printed once in the browser screen.

image.png

If you change the condition by modifying while (x<1) to while (x>1), the loop should run three times executing the statement inside it three times. And if you run the same code in your browser you can expect the following output:

image.png



0
0
0.000
0 comments