Home

ABCs of Programming Constructs

Looping Containers

FOR LOOPS, WHILE / DO WHILE LOOPS, and FOR...IN / FOR...EACH LOOPS are all CONTAINERS to REPEAT lines of code.

A. For Loops

There are two major type of "for" loops:

  1. "for" loop
  2. "for...in" loop

The most popular type of loop statement is the for loop with the "while" loop being a close second. The "for" loop executes a FINITE number of times.

In the “for” loop, you need to know the three I’s of looping:

  1. Initiate counter index  – var i = 0; – an initialize the counter start value. This is set only ONCE regardless of the number of loops
  2. Iterate condition for loop –  i < myArray.length – a test conditional statement. This is the test condition that return a true or false that is typically assign to the lenght value of an array. If true the loop continue. If false the loop stops.
  3. Increment by 1 –  i++ – an increment statement updates the value of the initial conter value for each loop by a certain amout (usually 1).

    NOTE: It is a common programming practice to use letters like i, j, k, etc for variables of a loop. Since these variables are only use for the loop, there is no need to give them a more descriptive name like counter.
for(var i = 0; i < 3; i++)
  {
    alert ("Hello, World") // Returns Hello, World three times
   }

Is is common practice to not hard wire the loop conditional value unless it is always the same (e.g. 7 for 7 days of the week or 12 for 12 months in a years, etc.). Most often the conditional statement is a dynamic variable that represents the total number of times the loop needs to execute. And since loops and arrays are used a lot together, you will often see the total number of elements of an array using its length property (e.g., myArray.length).

var myArray = ["apple", "banana", "orange"]
for(var i = 0 ; i < myArray.length ; i++)
  {
    alert (myArray[i]); // Returns apple, banana, orange
   }

NOTE: As mentioned earlier, arrays are "kissing cousins" with loops because they are often used to popular arrays OR to get element values from an array.

While not the case in some books that you may read, it is best practice to place the initial value variable and the condition statement variable outside the loop in order to make the loop easier to read and faster to execute because the variables do not have to be "processed" each time the loop iterate.

var myArray = ["apple", "banana", "orange"]
var i;
var total = myArray.length;
for( i = 0 ; i < total ; i++)
  {
    alert (myArray[i]); // Returns apple, banana, orange
  }

NOTE: To decrement (count down) instead of increment (count up) a loop counter review the following syntax. The code will count down from 10 to 1. Notice that to reverse a loop, you basically reverse all four of these items from a traditional loop:

  1. the start value is the largest value (10) instead of zero (0)
  2. the sign is greater than (>) instead of less than (<)
  3. the condition statement value is zero (0) instead of (10)
  4. the increment type is decrement (--) instead of (++)
var i;
for(i = 10; i > 0 ; i--)
  {
     alert("CountDown: " + i); // Returns CountDown: 10, 9, 8, 7...
  }

While the break statement can be used to exit a switch statement (discussed later), it can also be used to break or exit a loop at any time and continues executing code after the loop if there is any.

Example:

for (var i=0; i<10 ; i++)
  {
    if (i==5)
  {
  break;
   }
    alert(i);  // Returns  0-4
   }

The continue statement is used to skip the remainder of the code and CONTINUE the next iteration statement. It can be used to SKIP a particular value from a series of values.

for (var i=0 ; i<10 ; i++)
  {
    if (i==5)
  {
  continue;
   }
      alert(i); // Returns  0-9 but NOT 5
    }

CAUTION: Once a loop is started, nothing else can be done until the loop is finished. As a result, you may not want to use them for updating graphics visually.  To "see" graphic update visually one at a time, you need to create a timer object that execute at a set frequency (e.g., setInterrval).

B. While / Do While Loops

The "while" loop – instead of executing a finite number of times, the "while" loop executes as long as an condition is met. In is basically an inverted "for" loop. In essence, while loops are loops with a conditional statements in it. The loop continues as long as the condition is true.

SYNTAX:

while (condition)
  {
    // code to repeat
   }

There are two type of "while" loops:

  1. "while" loop
  2. "do...while" loop
var i = 0;
while (i < 10)
  {
    alert("i =" + i); // Returns i = 0, i= 1...
    i++
  } 

COMMENTS ON CODE: What the code above is saying in essence is:

  1. Start i at 0 (var i = 0;)
  2. then WHILE "i" is less than  twenty (while (i < 20)) condition is STILL TRUE
  3. execute what is in the code block ( { // do something including incrementing "i" by 1 (i++))
  4. otherwise, stop the loop

"do/while" loop –  is basically the same as the while loop. The different is the conditional statement is placed AFTER the loop ensuring the code block executes  AT LEAST ONE TIME EVEN if  the condition is FALSE because the code is executed BEFORE the condition is tested.  The condition is not ran until the code runs at least one time. 

SYNTAX:

do {
      // code to repeat
      }
while (condition)

MEMORY TIP: DO something at least ONCE in a WHILE.

var i = 0;
do {
        alert("i =" + i); // Returns i = 0, i= 1...
        i++
       }
while (i < 10) 
C. For...In / For...Each Loops

For..In Loop

The regular "for" loop is useful when the number of iteration is known. The "for..in" loop iterates through the properties values of an object or an array.

SYNTAX:

for (var property in object)
  {
     // loop through object property
   }

EXAMPLES:

var myObject:Object = new Object()
myObject.firstName = "Bob"
myObject.lastName = "Jones"
myObject.city =  "Dallas"

Or you can use an literal array

var myObject = {firstName:"Bob", lastName:"Jones", city:"Dallas"}
for (var prop in myObject)
  {
    alert (prop + "= " + myObject[prop]); // firstName = Bob , lastName = Jones, city = Dallas
  }

CAUTION: The for...in loop can be used for an array. If the output of the elements ORDER is important, it may be best to loop through an array instead of an object. Notice that if you use an associative array, the order of the property in the array is in reverse order.

NOTE: Some programming languages support a variation of the for...in loop called the for...each loop.

Key points to remember about loops:

< Previous Topic     Next Topic >