Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

JavaScript for loop

The JavaScript for loop iterates the elements for the fixed number of times.

JavaScript for loop should be used if number of iteration is known.

for loop repeats until a specified condition evaluates to false.

This tutorial focuses on JavaScript for loop. 

The JavaScript for loop is similar to the Java and C for loop.

Syntax

for (initialExpression; condition; updateExpression) {
    // for loop body
}

initialExpression: The loop initialization where we initialize our counter to a starting value. It executes only once. The initialization statement is executed before the loop begins.

The  condition statement which will test if a given condition is true or not. If the condition is false, the for loop is terminated. If the condition is true, the block of code inside of the for loop is executed.

The updateExpression updates the value of initialExpression when the condition is true. It is also called the iteration statement where you can increase or decrease your counter.

The condition is evaluated again. This process continues until the condition is false.

Flowchart

JavaScript for loop flowchart

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript for loop example</title>
</head>

<body>
    <script>
        var count;
        document.write("Starting Loop" + "<br />");

        for (count = 0; count < 10; count++) {
            document.write("Current Count : " + count);
            document.write("<br />");
        }
        document.write("Loop stopped!");
    </script>
    <p>Set the variable to different value and then try...</p>
</body>

</html>
JavaScript for loop example – output