Javascript Do While Loop Code Syntax Example

In my previous articles i have described about javascript For Loop and While Loop. In this Javascript Tutorial i am going to explain all about Do While Loop. The main concept for every loop is to iterate statement(s) repeteadly. The basic difference among While Loop, For Loop and Do While Loop is, While Loop and For Loop check the condition before every iteration but Do While loop check the condition after every iteration. So the main concept is, Do While loop at least iterate the underlying statement(s) once where as While loop or For loop does not iterate the underlying statement(s) without checking the condition first.

Overview of Do While Loop:
javascript_Do_While_Loop_General

Note: As i have mentioned earlier that Do While Loop must be executed once because this loop check the condition after each iteration. Code executes sequentially. If you look at the above Do While Loop code syntax, you will find that the condition is the last line of loop block. So its very clear that the loop statements will execute once before checking the condition. If you need to write multiple statements you have to enclose within curly braces like other loops.

Incremental Do While Loop Example:

<script type="text/javascript">
    // This is the incremental do while loop
    var i=0;
    document.write("***** Start Do While loop *****</br>");
    do{
        document.write("Iteration Number = " + i+"</br>");
        i++; // i++ means i=i+1
    }while(i < 5)
    document.write("***** End Do While loop *****");
</script>

Output:
javascript_Do_While_Loop_Incremental

Decremental Do While Loop Example:

<script type="text/javascript">
    // This is the decremental do while loop
    var i=4;
    document.write("***** Start Do While loop *****</br>");
    do{
        document.write("Iteration Number = " + i+"</br>");
        i--; // i-- means i=i-1
    }while(i >= 0)
    document.write("***** End Do While loop *****");
</script>

Output:
Javascript_do_while_loop_Decremental

Using break in a Do While Loop:
As we knew that from any statement we can exit from loop even the condition still true. To do so we need to use break statement. But if you use BREAK (in uppercase) instead of break you will be executed from whole script.

<script type="text/javascript">
    var i=0;
    document.write("***** Start Do While loop *****</br>");
    do{
        document.write("Iteration Number = " + i+"</br>");
        if(i==3)
            break;
        i++;
    }while(i < 5)
    document.write("***** End Do While loop *****");
</script>

Output:
javascript_do_while_loop_break

Download Code Example

Posted in Client, Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*