We now have a youtube channel. Subscribe!

JavaScript For Loop


Hello guys! afternoon and welcome to this new tutorial post on JavaScript. In my last tutorial post i talked about JavaScript while loop, now let's quickly take a look at another form of loopingcalled for loop.

The for loop is the most compact form of looping. It is made up of three important parts which are listed out below:

  • The text statement which will text if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
  • The iteration statement where you can increase or decrease your counter.
Note: you can put all the three parts in a single line separated by semicolons.

You can check out our tutorial post on: JavaScript Operators

Flow Chart

Below is the flow chart of JavaScript for loop statement.


Syntax

The syntax of for loop in JavaScript is as follows:

for   (initialization;    test condition;   iteration statement)  {
       Statement(s) to be executed if test condition is true 

Example

Below is a brief example that shows how to implement a for loop statement in JavaScript:

You can also read our tutorial post on: Css Positioning


<html>
     <body>
          <script    type="text/javascript">
               <!--
                    var   count; 
                    document.write("Starting Loop " + " <br />");

                    for ( count = 0;    count  <  8;    count++)  {
                           document.write("Current Count: "  + count); 
                           document.write("<br />");
                    }
                    document.write("Loop stopped!");
               //-->
          </script>
     </body>
</html>

You can try the above example with your text editor for better understanding. Also feel free to drop your questions in the comment box, they will be attended to as soon as possible.

Below is the output of the above example:

Starting Loop
Current Count:  0
Current Count:  1
Current Count:  2
Current Count:  3
Current Count:  4
Current Count:  5
Current Count:  6
Current Count:  7
Loop stopped!

Alright guys we have come to the end of this tutorial post on JavaScript for loop. Always feel free to drop your questions in the comment box, they will always be attended to.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain