JavaScript supports different kinds of loops:
for - loops through a block of code a number of times;
for/in - loops through the properties of an object;
while - loops through a block of code while a specified condition is true;
do/while - also loops through a block of code while a specified condition is true.
For Loop: In the code below, for loop to go through all elements of array is implemented. We can use length property of JavaScript array to detect number of elements in array.
<script>
var person=new Array(); person[0]="sourav"; person[1]="Sathis";
person[2]="Nontey"; for(var i = 0;i< person.length;i++)
{ document.write("Person " + i + ": "+ person[i] + "<br>"); }
</script>
While Loop: In case of while loop there is only one condition within while() statement.
<script>
var person=new Array(); person[0]="sourav"; person[1]="Sathis";
person[2]="Nontey"; for(var i = 0;i< person.length;i++)
var i =0;
document.write("Using While loop" + "<br>");
while(i < person.length)
{document.write("Person " + i + ": "+ person[i] + "<br>");i++;} </script>
Do-While Loop: Do while is very similar with While loop but do- while is post checking loop. So, even if your condition is false loop will execute at least one time.
<script>
var person=new Array();
person[0]="sourav"; person[1]="Sathis"; person[2]="Nontey";
var i =0; document.write("Using Do-While loop" + "<br>");
do { document.write("Person " + i + ": "+ person[i] + "<br>");
i++; }while(i< person.length);
</script>