Blog

Loops in JavaScript

JavaScript supports the 3 loops normally used in programming. The for loop, while loop and the do while loop.

ForLoop Consider the following for loop:
var output=””;
for(var i=1;i<=10;i++)
output=output + “,” + i;

The four parts of this loop are:

  1. var i=1; Loop Initialization
  2. i<=10; Loop Condition
  3. output=output + “,” + i; Loop body
  4. i++; Increment/Decrement

The parts are executed in this order:

  1. Initialization;
  2. Condition: if true go to 3 else go to 5
  3. Body
  4. Increment/Decrement go to 2
  5. Statements after the for loop

The while loop has the following format:
while(condition)
Statement;
If there are more than one statements to be repeated then:
while (condition)
{
Statement1;
Statement2;
.
.
.
}

The do while loop is written in such a way that the loop runs at least once. the condition is checked at the end.
do
{
Statement1;
Statement2;
.;
.;
}
while(condition);
Try the loops at this page:
Loops in Java Script

Leave a Reply

Your email address will not be published. Required fields are marked *