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:
- var i=1; Loop Initialization
- i<=10; Loop Condition
- output=output + “,” + i; Loop body
- i++; Increment/Decrement
The parts are executed in this order:
- Initialization;
- Condition: if true go to 3 else go to 5
- Body
- Increment/Decrement go to 2
- 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