JavaScript Loops


JavaScript loops are used to iterate a block of code multiple number of times using for, while, do while or for-in loops.

There are four types of loops in JavaScript:

1. for loop
2. while loop
3. do-while loop
4. for-in loop


JavaScript for loop

JavaScript for loop iterates the block of code for the fixed number of times. It should be used if number of iterations is known before.

Syntax:

    for ( initializer, condition, iteration )
    {
        //code to be executed
    }    


The for loop requires following three parts:

• Initializer: Initialize a counter variable with a starting value.

• Condition: tests the condition that must evaluate to true for next iteration to be executed.

• Iteration: increase or decrease the counter.



Example:

    for ( i = 0; i < 5; i++ )
    {
        document.write ( i + “  ” );
    }        

The above example will output: 0 1 2 3 4.


JavaScript while loop

JavaScript while loop iterates the block of code repeatedly till it satisfies the specified condition. It is used when the number of iterations is not known before.

Syntax:

    while ( condition )
    {
        //code to be executed
    }    


Example:

    var i = 0;
    while ( i < 5 )
    {
        document.write ( i + “  ” );
        i++;
    }    

The above example will output: 0 1 2 3 4.



JavaScript do-while loop

JavaScript do while loop iterates the block of code repeatedly till it satisfies the specified condition present after the code.

This loop will execute the block of code at least once since the condition is checked after execution of code block.

Syntax:

    do{
        //code to be executed
    }while ( condition );    


Example:

    var i = 0;
    do {
        document.write ( i + “  ” );
        i++;
    } while ( i < 5 );    

The above loop will output: 0 1 2 3 4.