Home > DeveloperSection > Articles > The for loop in JavaScript

The for loop in JavaScript

JavaScript JavaScript 
0 Comment(s)
 1914  View(s)
Rate this:

The for loop in JavaScript


The for loop is very popular looping constructs and it is widely used also when we want execute same block of code over and over again.

Syntax of For Loop

for (Initialization; condition; Iteration statement)


 code to be executed   //if the condition is true


It has three parts:

1)                  Initialization Statement

2)                  Condition Statement

3)                  Iteration  Statement

In Initialization Statement we initialize our counter variable for eg. i=0; The initialization statement is the first statement and it is executed before the code given inside the loop is executed.

Condition Statement or test statement specifies the test criteria for the body part to keep executing. Till the time the Test Statement is true loop will continue executing as soon as the condition becomes false  the code which are written inside the loop stops working.

Iteration Statement iterates or decrements the counter variable by a specific number for eg. (i++ or i--). Each time our loop executes it either increments it or decrements it as the requirement arrises.

Example of For loop:

<html xmlns="http://www.w3.org/1999/xhtml">



    <script type="text/javascript">

        function forloop() {

            var a;

            document.write("For loop started" + "<br />");

            for (a = 0; a <= 5; a++) {

                document.write("a's value is" + a);

                document.write("<br />");


            document.write("For loop exited");






        <input id="btnLoop" type="button" value="button" onclick="forloop()" />





In this example, the first section initializes variable a with a value 0,  Second part of the for loop is to check the condition i.e. (a<=5), so till the condition satisfies a is less than or equal to 5 the loop will execute and  as soon as a’s value reaches more than 5 then the condition becomes false and the loop will exit.

Output of the above Program:

The for loop in JavaScript


Through this article we came to know the working of for loop, how to initialize it and check condition.  For loop is mostly used in all programming language because it is simple and easy to use.

Don't want to miss updates? Please click the below button!

Follow MindStick