Loops in JavaScript

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:

Iterative Method

Iterative method to do this is to write the document.write() statement 10 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type = "text/javascript">
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
< /script>

chevron_right


Using Loops

In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type = "text/javascript">
var i;
  
for (i = 0; i < 10; i++) 
{
    document.write("Hello World!\n");
}
< /script>

chevron_right


Many things may seem confusing to you in the above program at this point of time but do not worry you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can observe that in the above program using loops we have used the document.write statement only once but still, the output of the program will be same as that of the iterative program where we have used the document.write statement 10 times.

In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.

  • An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
  • Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeat it.
  • Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.

There are mainly two types of loops:

  1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop body. For Loop and While Loop are entry controlled loops.
  2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test condition is true or false. do – while loop is exit controlled loop.

JavaScript mainly provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. Let us learn about each one of these in details.

  1. while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
    Syntax :

    while (boolean condition)
    {
       loop statements...
    }
    

    Flowchart:
    while loop

    • While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop
    • Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
    • When the condition becomes false, the loop terminates which marks the end of its life cycle.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script type = "text/javaScript">
    // JavaScript program to illustrate while loop
      
        var x = 1;
      
        // Exit when x becomes greater than 4
        while (x <= 4)
        {
            document.write("Value of x:" + x + "<br />");
      
            // increment the value of x for
            // next iteration
            x++;
        }
      
    < /script>

    chevron_right

    
    

    Output:

    Value of x:1
    Value of x:2
    Value of x:3
    Value of x:4
    
  2. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
    Syntax:

    for (initialization condition; testing condition; 
                                  increment/decrement)
    {
        statement(s)
    }
    

    Flowchart:
    for-loop-in-java

    1. Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
    2. Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
    3. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
    4. Increment/ Decrement: It is used for updating the variable for next iteration.
    5. Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script type = "text/javaScript">
    // JavaScript program to illustrate for loop
      
        var x;
      
        // for loop begins when x=2
        // and runs till x <=4
        for (x = 2; x <= 4; x++) 
        {
            document.write("Value of x:" + x + "<br />");
        }
      
    < /script>

    chevron_right

    
    

    Output:

    Value of x:2
    Value of x:3
    Value of x:4
    

    for…in loop

    JavaScript also includes another version of for loop also known as the for..in Loops. The for..in loop provides a simpler way to iterate through the properties of an object. This will be more clear after leaning objects in JavaScript. But this loop is seen to be very useful while working with objects.

    Syntax:

    for (variableName in Object)
    {
        statement(s)
    }
    

    In each iteration, one of the properties of Object is assigned to the variable named variableName and this loop continues until all of the properties of the Object are processed. Lets take an example to demonstrate how for..in loop can be used to simplify the work.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script type = "text/javaScript">
    // JavaScript program to illustrate for..in loop
      
        // creating an Object
        var languages = { first : "C", second : "Java"
                          third : "Python", fourth : "PHP"
                          fifth : "JavaScript" };
      
        // iterate through every property of the
        // object languages and print all of them
        // using for..in loops
        for (itr in languages) 
        {
            document.write(languages[itr] + "<br >");
        }
      
    < /script>

    chevron_right

    
    

    Output:

    C
    Java
    Python
    PHP
    JavaScript
    
  3. do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.
    Syntax:

    do
    {
        statements..
    }
    while (condition);
    

    Flowchart:
    do-while

    1. do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
    2. After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
    3. When the condition becomes false, the loop terminates which marks the end of its life cycle.
    4. It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script type = "text/javaScript">
    // JavaScript program to illustrate do-while loop
      
        var x = 21;
      
        do 
        {
            // The line while be printer even
            // if the condition is false
            document.write("Value of x:" + x + "<br />");
      
            x++;
        } while (x < 20);
      
    < /script>

    chevron_right

    
    

    Output:

    Value of x: 21
    

Infinite loop

One of the most common mistakes while implementing any sort of looping is that that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.
Examples:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type = "text/javaScript">
// JavaScript program to illustrate infinite loop
  
    // infinite loop because condition is not apt
    // condition should have been i>0.
    for (var i = 5; i != 0; i -= 2)
    {
        document.write(i);
    }
      
    var x = 5;
  
    // infinite loop because update statement
    // is not provided.
    while (x == 5) 
    {
        document.write("In the loop");
    }
  
< /script>

chevron_right




My Personal Notes arrow_drop_up

Senior Technical Content Engineer | GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.