JavaScript Lesson 8: Looping

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>

Another kind of decision-making procedure in JavaScript is 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

<html>
<head>
<title>For Loop</title>
</head>
<body>
<script language='javascript'>
var sum=0
for (n=0; n<11; n++)
 { sum+=n   }
 document.write("sum="+sum)
</script>
</body>

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) {statements}

 

Example 8.2: Retrieving the properties of document

<html>
<head>
<title>For...In Loop 1</title>
</head>
<body>
<script type="text/javascript">
for (property in document)
 { document.write(property)
 document.write('<br>')
}
</script>
</body>

The above JavaScript code will display the properties of the document object in the browser window.

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. I will illustrate the algorithm using the example bellow. 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:

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

var sum,
mark1,
mark2,
counter,
avg;

sum=0;
counter=1;

while(counter<=8) {

mark1=window.prompt("Enter your mark","0");
mark2=parseInt(mark1);
sum=sum+mark2;
counter=counter+1;
}
avg=sum/8;
document.writeln("<H2> Average mark is "+avg+"</H2>");

</script>
</head>

<body>

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

</body>

</html>

Click on the testing page



<Previous Lesson> [Table of Contents] <Next Lesson>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone