Home > JavaScript > JavaScript Loops

JavaScript Loops

There are three methods for making a loop with JavaScript. There is a list of all loop structures in JavaScript:


I. While loop
II. Do … While loop
III. For loop

I. While Loop

This statement can be very useful if you don’t have or don’t know number of repetitions because it loops the operations while specified conditions are true.

Structure 1.0 :

1
2
3
4
5
while( conditions ){
//…
//operations
//…
}

There is a simple code example that shows us how to use while loop in JavaScript.

Example 1.0 :

1
2
3
4
5
var k=0;
while (k<=5){
document.write("The number : " + k+"<br/>");
k++;
}

Output of Example 1.0 :

1
2
3
4
5
6
Number : 0
Number : 1
Number : 2
Number : 3
Number : 4
Number : 5

II. Do … While Loop

There is a little but important difference between while loop and do…while loop With do…while loop, conditions are tested at the end of the loop. The loop is always executed at least once with this using.

Structure 2.0:

1
2
3
4
5
do{
//…
//operations
//…
}while( conditions )

Example 2.0 :

1
2
3
4
5
var i=1;
do{
document.write("The Number : " + (i*3) + "<br/>");
i=i+1;
}while(i<4)

Output of Example 2.0 :

1
2
3
Number : 3
Number : 6
Number : 9

III. For Loop

The for loop depends on a counter ( that increases or decreases by the same amount each time through the loop ) and loops the operations until the counter reaches a specified value.


Structure 3.0:

1
2
3
4
5
for(initialization; conditions; increment){
//...
//operations
//...
}

Example 3.0:

1
2
3
4
5
6
7
var i=0
document.write("The numbers: ");
for (i=0;i<=10;i++)
{
document.write(i);
if(i!=10)document.write(", ");
}

Output of Example 3.0:

1
The numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

IV. Break and Continue Statements in Javascript Loops


4.1 ) Break Statement

Break statement is used for exiting from the loop that contains the break statement immediately.

Example 4.0

1
2
3
4
5
6
7
var i;
document.write("The numbers: ");
for (i=0;i<=10;i++)
{
document.write(i+" ");
if(i==6)break;
}

Output of Example 4.0:

1
The numbers: 0 1 2 3 4 5 6

Example 4.1

1
2
3
4
5
6
var i;
document.write("The numbers: ");
for (i=0;i<=10;i++)
{ if(i==6)break;
document.write(i+" ");
}

Output of Example 4.1:

1
The numbers: 0 1 2 3 4 5

As you see in the Example 4.0 and Example 4.1 the loop is broken when the break statement is read.

4.2 ) Continue Statement

Continue statement is used for skipping from the loop that contains the continue statement immediately..

Example 4.2

1
2
3
4
5
6
var i;
document.write("The numbers: ");
for (i=0;i<=10;i++){
if(i==6)continue;
document.write(i+" ");
}

Output of Example 4.2:

1
The numbers: 0 1 2 3 4 5 7 8 9 10

In the example 4.2, when i reaches 6, operation is skipped and 6 is not written.

Bookmark and Share
Categories: JavaScript Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker