The 'for' statement

The 'for' statement is conceptually identical to the 'while' statement, with only a slight difference in implementation. For loops are generally used to execute a series of instructions for a specified number of iterations. While loops are often used in situations where the time of exit from the loop is not known beforehand. You will notice, however, that any situation requiring a loop can be satisfied by any of the looping constructs. In practice, though, some situations are better suited for certain loops; these will become more clear with experience. The 'for' statement has the following syntax:

Syntax:

  for(initial; condition; iteration) 
       statement;

The 'for' statement introduces the concept of an initial statement. When the program execution reaches a 'for' statement, the 'initial' statement is the first to be executed, but only on the first iteration. Most often, the 'initial' statement creates and/or sets a variable to a specific value. As in the preceding examples, 'condition' is the conditional statement that is evaluated preceding each loop, and determines whether another iteration will occur. The 'iteration' statement is executed after the completion of the last statement within the loop, but before 'condition' is evaluated again. Generally, the iteration statement is used to move the conditional closer to an exit. Returning to the counting example, using a for loop instead of a while loop to count to 20 would look like this:

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

// Loop from 1 to 20
// Analysis

for(var counter=1; counter <= 20; counter++)
	document.writeln(counter + "<br>"); 

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

 

Notice how the for loop is more suitable for the counting example. All of the necessary elements -- initialisation, conditional evaluation and iteration -- are handled in a single statement. The first encounter with a for loop can be a little intimidating, but it is likely to become the most frequently used looping construct in your programs.