JavaScript for loop

In the previous tutorial we have seen about:

  1. Javascript while loop and
  2. JavaScript do-while loop.
In this section, you will learn about the description, flow charts, and syntax of for loop with different examples.

The JavaScript for loop has three crucial parts, and it is the minimized/compacted form of looping statement.

  1. Initialization part: is used for declaring and initializing variables.
  2. Condition/Expression: This is used for Evaluating or testing whether the condition is true or false.
  3. Iteration: This part is used for increment or decrement of our counter.
Flow chart of for loop


Syntax
for (initialization; condition; iteration(inc/dec);) {
   statement;
}
Example1:Display the first five natural numbers.
<html>
    <head>
        <title>JS for loop</title>
    </head>
    <body>
        <script>
            document.write("--Start--"+"</br>");
            for (let i = 1; i <=5; i++) {
                document.write("Iteration:"+i+"</br>");
                document.write("</br>")
                
            }
            document.write("--End--");
        </script>
    </body>
</html>
Output
Example2: Display a text three times
<html>
    <head>
        <title>JS for loop</title>
    </head>
    <body>
        <script>
             var text="JS tutorial!"
            for (let i = 1; i <=3; i++) {
                document.write(text+"</br>"); 
            }
        </script>
    </body>
</html>
Output 
Example3: Display the sum of the first 100 natural numbers.
<html>
    <head>
        <title>JS for loop</title>
    </head>
    <body>
        <script>
            var sum=0;
            for (let i = 1; i <=100; i++) {
                sum+=i;  
            }
            document.write("Sum="+sum); 
        </script>
    </body>
</html>
Output