Table of Contents

    Mastering the JavaScript For Loop: A Comprehensive Guide

    JavaScript For Loop

    JavaScript For Loop is used to execute a block of code for a number of times based on a condition.

    In this tutorial, we will learn how to define/write a JavaScript For loop, and its usage using example programs.

    Syntax

    The syntax of JavaScript For Loop is

    
    for (initialization; condition; update) {
         //statements
     }
    

    where

    • initialization can contain one or more variables defined and initialized.
    • condition is the expression which is checked before executing the statements inside for loop.
    • update can contain increment, decrement, or any update to the variables. Variables defined in the initialization part can be updated here. update section is executed after executing the statements inside for loop.

    Please note that all the three: initialisationcondition, and update are optional in a for loop statement.

    Examples

    In the following example, we execute a block of code that appends ‘hello world’ to a pre block HTML element ten times using a For Loop.

    
    <!DOCTYPE html>
    <html lang="en">
    <body>
        <pre id="output"></pre>
        <script>
            for (let i = 0; i < 10; i++) {
                document.getElementById('output').innerHTML += 'hello world\n';    
            }
        </script>
    </body>
    </html>
    

    Output:

    If you will run above code, you will get below output.


    We can also use a for loop to iterate over the elements of an array, using array length in condition, as shown in the following example.

    
    <!DOCTYPE html>
    <html lang="en">
    <body>
        <pre id="output"></pre>
        <script>
            var arr = [10, 20, 30, 40];
            for (let i = 0; i < arr.length; i++) {
                document.getElementById('output').innerHTML += arr[i] + '\n';    
            }
        </script>
    </body>
    </html>
    

    Output:

    If you will run above code, you will get below output.