Thursday, June 21, 2012

Java Script Tutorial 11 : JavaScript For Loop

When you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform tasks. There are two different kind of loops, we use in JavaScript, these are as follows :
  1. for 
  2. while
We discuss only for loop in this tutorial.


The for Loop :
The for loop is used when you know in advance how many times the script should run. Syntax of for loop is as follow :


for ( variable = startvalue; variable<endvalue;variable = variable + increment)
  {
       code to be executed
  }


For example


for (i=0; i<3; i++)
  {
  y=y + "The number is " + i + "<br />";
  }


This for loop runs 3times, and write results in every new line. The result of above code will be :


The number is 0
The number is 1
The number is 2

No comments:

Post a Comment