JavaScript Loops


The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact. It is mostly used in array.

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

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known. The syntax of for loop is given below.

Let’s see the simple example of for loop

    <!DOCTYPE html>
    <html>
    <head>
        <title>for loop</title>
    
        <script>  
        for (i=1i<=5i++)  
         {  
          document.write(i + "<br/>")  
         }  
        </script>  
    
    </head>
    <body>


    </body>
    </html>

The While Loop

Loops can execute a block of code as long as a specified condition is true. The while loop loops through a block of code as long as a specified condition is true.

Example

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:

    <!DOCTYPE html>
     <html>
        <body>

        <h2>JavaScript While Loop</h2>

            <p id="demo"></p>

        <script>
            let text = "";
            let i = 0;
                        while (i < 10) {
             text += "<br>The number is " + i;
             i++;
            }
            
            document.getElementById("demo").innerHTML = text;
        </script>

    </body>
    </html>

The Do While Loop

The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Example

The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

    <!DOCTYPE html>
    <html>
    <body>
        <h2>JavaScript Do While Loop</h2>
    <p id="demo"></p>

    <script>
        let text = ""
        let i = 0;

        do {
          text += "<br>The number is " + i;
          i++;
        }
        while (i < 10);  

        document.getElementById("demo").innerHTML = text;
    </script>

    </body>
    </html>