JavaScript Loops


Loops can execute a block of code a number of times.


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.

The For Loop

The for loop is often the tool you will use when you want to create a loop.

Syntax

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

Example

<script type="text/javascript">
for (i=1; i<=5; i++)  
{  
document.write(2 +" * " + i + " = " + 2*i +  "<br>")   
}  
</script>  
Output
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10

The For/In Loop

The JavaScript for/in statement loops through the properties of an object.

Syntax

for (variablename in object) {
  statement or block to execute
}

Example

<script type="text/javascript">
var student = { stud1:"Ashwani", stud2:"Sachin"};
var names = ""
var a;
for (a in student)
  {
    names += student[a]+ " / ";
}
document.write(names);
</script> 
Output
Ashwani Sachin 

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition) {
    code  to be executed
}

Example

<script type="text/javascript">
var i = 1;  
while (i < = 5)  
{  
document.write(i + "<br>");  
i++;  
}  
</script> 
Output
1
2
3
4
5

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
    code to be executed
}
while (condition);

Example

<script type="text/javascript">
    var i=15;  
    do {  
    document.write(i + "<br/>");  
    i++;  
    } while (i<=20); 
</script>  
Output
15
16
17
18
19
20

Share this article on