The 'while' loop

The 'while' statement is used to execute a series of instructions as long as a specified condition evaluates to True. The syntax for the 'while' statement is:

Syntax:

  while(condition)
       statement;

The condition in the example above is a statement that evaluates to True or False, and is usually constructed out of relational and logical operators. If 'condition' evaluates to True, then 'statement' is executed and the process repeats. If the condition evaluates to False, execution moves on to the next statement after the loop. In most cases, 'statement' will be a statement (or grouping of statements) that has the potential to alter the condition and exit the loop.

Last month we introduced the idea of using brackets to group together several statements. Two of the most common uses for this are grouping statements in conditionals (such as the 'if' statement) and in looping statements (such as the While statement). The 'while' statement is used in the following script to count from one to 20.

<html>
<head>
<title>While loop example</title>
</head>
<body bgcolor="#FFFFFF">
<script language="JavaScript">
<!-- Hide code

// Create a counter variable
// Analysis

var counter = 1;

// Count from 1 to 20
// Analysis

while(counter <=20)
	{
	document.writeln(counter + "<br>"); 
	counter++;
	}

//  End script -->
</script>
<body>
</html>

 

This example shows a simple use of the 'while' statement. The variable 'counter' is initialised to '1' at the start of the program. The 'while' statement then checks to see if 'counter' is less than or equal to 20. If the condition is true - that is, 'counter' is <= 20 - then the value of 'counter' is written to the screen, followed by the HTML for a line break. Then, 'counter' is incremented by one, using the unary increment operator, and the condition is evaluated again. When (and if) the condition evaluates to False, execution moves to the next statement after the while loop (</script>).

It is important to notice in the example that the same two statements executed at different times have a completely different effect on the execution of the program. On the first iteration of the loop, the 'writeln()' method will write '1' to the screen. The same statement executed at a different time will write '14' to the screen. Later we will see how to use numerical values to access different data structures, where the power of looping statements is truly unleashed.