Difference between JavaScript While and Do While loop

Difference between JavaScript While and Do While loop with example?. Though Do While loop and While loop looks similar, they differ in their execution.

  • In While loop, the condition tested at the beginning of the loop, and if the condition is True, statements inside the loop will execute. It means the While loop executes the code block only if the condition is True.
  • At the end of the loop, the Do While loop tests the condition. So, Do While executes the statements in the code block at least once even if the condition Fails.

I think you will understand it completely when you see the example. So, let’s write the same program using While loop and Do While loop

JavaScript While Loop Example

In this JavaScript program, we are declaring an integer and then check whether One is greater than Ten or not. If the condition is True, it has to display the Output as “X is Greater Than 10”. There is one more statement outside the While loop, and it will run after the while loop.

<!DOCTYPE html>
<html>
<head>
    <title> Difference between JavaScript While and Do While loop </title>
</head>

<body>
    <h1> JavaScript While Loop </h1>
<script>
    var x = 1;
    while (x > 10)
    {
        document.write("<br\> <b> X Is greater Than 10 </b>");
    }

    document.write("<br\> <b> Statement Outside the while loop </b>");
</script>
</body>
</html>
JavaScript While Loop 

Statement Outside the while loop

JavaScript Do While Loop Example

We are going to write the same JavaScript example using Do While loop

<!DOCTYPE html>
<html>
<head>
    <title> Difference between JavaScript While and Do While loop </title>
</head>

<body>
    <h1> JavaScript Do While Loop </h1>
<script>
    var x = 1;
    do
    {
        document.write("<br\> <b> X Is greater Than 10 </b>");
    }while (x > 10);
    
    document.write("<br\> <b> Statement Outside the while loop </b>");
</script>
</body>
</html>
Difference between JavaScript While and Do While loop 2

Although the Do while loop condition fails, the statement inside the loop is executed once. Because after the execution of the statements, the compiler tested the condition.

Comments are closed.