JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 8: Looping

We have learned about decision-making procedure using conditional operators in the previous lesson. In this lesson, we shall examine another kind of decision-making procedure in JavaScript, i.e looping. Looping is a procedure whereby the execution is repetitive and will only terminate until a certain condition is met. There are two types of loops, the for loop and the while loop.

8.1 The for Loop

The for loop lets JavaScript executes the statements repeatedly until it meets a certain condition. The syntax is:

for (initial expression; condition expression; loop expression)
{ Statements}

Example 8.1

<title>For Loop</title>
<script language='javascript'>
var sum=0
for (n=0; n<11; n++)
 { sum+=n   }

In the above example, the initial expression is n=0, the condition expression is n<11 and the loop expression is n++. It means the loop will stop only when n is more than 11. The statement sum+=n means n is added to the sum in every repetition. Finally, the browser will display the final value of the sum, which is 55 in this example.

8.2 The for in Loop

The for in loop is a special loop that is used to retrieve the properties of JavaScript objects. The syntax to retrieve the object is

for (property in object)

Example 8.2: Retrieving the properties of document

<title>For...In Loop 1</title>
<script type="text/javascript">
for (property in document)
 { document.write(property)

The above JavaScript code will display all the properties of the document object in the browser window, as shown below.

8.3 The While Loop

The while statement allows us to control the number of times a procedure is performed. It is important to make that the repetition is not endless. The algorithm is illustrated in example 8.3. The program will produce a pop-up dialog box 8 times prompting the user to enter the marks 8 times, then it will add up the marks and show the average mark.

Example 8.3

<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Sample JavaScript using While</title>

var sum,


while(counter<=8) {

mark1=window.prompt("Enter your mark","0");
document.writeln("<H2> Average mark is "+avg+"</H2>");



<h2 align="center"><font face="Arial">Sample JavaScript using While</font></h2>



Click the "Start" button to begin entering the marks and calculate the average mark

Your average mark is :

❮ Previous Lesson Next Lesson ❯

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy