Loops: Repeating Statement Execution


Every programming language provides a method to do things repeatedly. For example when checking for valid user data, it may be necessary to examine every character of a string, one character at a time, until the end of the string is reached. Typically this is done inside a loop statement of some sort using a variable as a counter to keep track of which character is to be checked. The counter variable may be incremented by one, each time through, so that the first character is examined the first time through the loop, the second character the second time, and so forth. Being able to repeatedly execute a statement or compound statement is an essential feature of programming.

The simplest loop statement is probably the while statement:

while(expression) statement

As long as the JavaScript expression inside the round brackets evaluate to true the statement is executed. More typically while loops contain a block or compound statement often (also referred to as the loop body) shown here in bold:

while(expression){
   statement
   statement
   statement
}

Before the compound statement or loop block is executed, the expression in the round brackets is evaluated. If it is true the block is executed. When the block is finished executing, the expression is reevaluated. If it is true the block is executed again. This process continues until the expression evaluates to false. At that point the loop block is not executed, the while loop is complete, and the next statement after the loop can be executed. The following is a very simple while loop:

<HTML>
<HEAD>
   <TITLE>Simple While Loop with Counter Variable</TITLE>
</HEAD>

<BODY>
<PRE>Output from a simple while loop with a counter variable:
<SCRIPT Language="JavaScript">
<!--

counter = 0
while (counter < 5){
   document.writeln(counter)
   counter++
}

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>

Controlling the Loop

In this example, the Loop is controlled by the counter variable. It is part of the expression: counter < 5. Here is the script again:

counter = 0
while (counter < 5){
   document.writeln(counter)
   counter++
}

The following describes how this particular while loop works:

counter = 0
Before executing the loop statement the counter variable is set to zero. This insures the loop body will be executed at least once because zero is less than 5.
while (counter < 5)
The expression counter < 5 is evaluated. Since zero is less than five, the expression evaluates to true, and the loop block will be executed.
document.writeln(counter)
Inside the loop block the first statement is executed, writing out the current value of the counter variable.
counter++
The counter variable is incremented by 1. In other words if it was zero when before this statement is executed, it will be equal to one afterwards. As this is the last statement in the block the while expression will be reevaluated. And since, 1 is less than 5 the loop block will be executed again.

This loop ends when the counter variable is incremented to five. At that point it is no longer less than five and the loop block will not be executed again.

Flow Charts

While flow charts have fallen out of fashion as higher level languages have become popular, the following flow chart below is provided to help make clear each step in the while loop example. By following the arrows and remembering the current value of counter the looping mechanism may become more obvious. If you are at all unsure how loops work, try "walking through" the flow chart one step at a time. Keep track of the value of counter and see how many times you loop until the script is done.

The cycle in the flow chart where the expression is true, the document is written to, the counter incremented, and the expression is evaluated again..., forms a sort of visual "loop" in the flow chart. Hence the name.

Infinite Loops

It is all too easy to create a loop that will go on forever executing the loop block. Whether done by accident or deliberately the result is that the Web page will never complete loading, the browser's controls/buttons may freeze, or the browser may crash altogether. Here is an example of an infinite loop that was likely created by mistake:

counter = 0
while (counter < 10){
   document.writeln(counter)

}

Since the counter variable is never changed inside the loop it will always be less than ten. The counter++ statement or something similar was forgotten. If you try this in a document you may have to use your operating system to shut down your browser. Here is an infinite loop that has been written on purpose:

while (true){
   document.writeln("Some message..")
}

Note that the test expression is simply the true value.

Checking Every Character in a String

While validating text strings is described elsewhere on this site, here is a short example that prints out each character of a string on a separate line. Note the test in the while loop uses the length property of the string object. Also, as the counter goes through values 0, 1, 2, etc. it is used in the charAt() method of the string object to retrieve the character in that position in the string. The character is stored in the chr variable and written out to the document in the next line. In this example the string is Hello World which has a length of 11 characters in positions 0 through 10. Since counter is initially set to 0 and is incremented by one at the end of each loop, counter will be set to the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 and the body of the loop will be executed. However, afert counter is set to 11 the test counter < str.length will fail and the loop body will not be executed again.

<HTML>
<HEAD>
   <TITLE>Examining Every Character in a String</TITLE>
</HEAD>

<BODY>
<PRE>Examining every character in a string:
<SCRIPT Language="JavaScript">
<!--

str = "Hello World"
counter = 0
while (counter < str.length){
   chr = str.charAt(counter)
   document.writeln(chr)
   counter++
}

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>

The chr variable contains a one character string - unlike languages like C where a single character is a different datatype. A small embellishment to this script might be to write out the value of the counter variable and the character at the same time. For completeness, the length of the string is written out when the loop ends. Output from this script shows the position of each character in the string and then the strings length:

<HTML>
<HEAD>
   <TITLE>Examining Every Character in a String</TITLE>
</HEAD>

<BODY>
<PRE>Examining every character in a string:
<SCRIPT Language="JavaScript">
<!--

str = "Hello World"
counter = 0
while (counter < str.length){
   chr = str.charAt(counter)
   document.writeln("Character in position " + counter + ": " + chr)
   counter++
}

document.writeln("The string length is: " + str.length)

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>