Tutorials Point

  JavaScript Basics
  JavaScript Objects
  JavaScript Advanced
  JS Useful References
  JS Useful Resources
  Selected Reading

Copyright © 2014 by tutorialspoint

  Home     References     Discussion Forums     About TP  

JavaScript for Loops

previous next AddThis Social Bookmark Button


We have seen different variants of while loop. This chapter will explain another popular loop called for loop.

The for Loop

The for loop is the most compact form of looping and includes the following three important parts:

  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.

  • The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.

  • The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by a semicolon.


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


Following example illustrates a basic for loop:

<script type="text/javascript">
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!");

This will produce following result which is similar to while loop:

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
Current Count : 8
Current Count : 9
Loop stopped! 

To understand it in better way you can Try it yourself.

previous next Printer Friendly