Address Book: Loops

Jason Atkins, Alyce Brady, Pamela Cutter, R.C. McDowell, Kelly Schultz and Nathan Sprague 1997, 1999, 2002, 2009, 2015
Kalamazoo College, Kalamazoo, MI

The For Loop

A for loop is used to repeat a set of statements a number of times. In JavaScript, a for loop looks like this:

Syntactic Structure:
for ( init; test; step )
for ( var i = 0; i < 10; i++ ) 
        document.writeln("i = " + i + "<br>");

The init expression initializes variables used in the loop, and is executed just once at the beginning of the loop. The test is a condition that is checked each time through the loop BEFORE we enter the loop body; if it is true the program executes the actionStatements in the loop body and if it is false it exits the loop. The step expression updates the loop variables for the next time through the loop – this is done immediately AFTER finishing the loop body and before the next evaluation of the test. The number of times the actionStatements in the loop body are executed depends on the initial values in the loop, how they are changed, and the logical expression in the test. One time through a loop is called an iteration. Here's an English description of how the different parts of the loop work:

  1. Initialize the loop variables (using the init expression).
  2. Check the test. If the test fails, exit the loop.
  3. Perform the actionStatements in the loop body.
  4. Update the loop variables (using the step expression).
  5. Go to step 2.

Example: Simple Loop

The purpose of the following code fragment is to write the values of the loop variable, from 0 through 4, to a web page.

// write values of i, from 0 to 4, each on a separate line
for (var i = 0; i < 5; i++)
    document.getElementById('dispAddresses').innerHTML +=
                    "i = " + i +
                    "<br />";

Try to identify the various parts of the loop. For example, what is the init expression, and what does it do? What is the test and when is it executed? What does the step expression do? What would this code fragment write to the web page? Ask the instructor or TA if you are unsure how to answer these questions!

Exercise 1 - Practice with Simple Loops
  1. In the head of the Address Book web page you created in the previous mini-lab, create a new function. This function will eventually print the contents of your address book, so give it a meaningful name that expresses this purpose. The function should take one parameter: the array of address book entries. For now, use the loop above as the body of the function. (This assumes that your page contains a div element with the id "dispAddresses". If you gave your div element a different id, then use that id name instead.)
  2. In the body of the web page, locate the statements you wrote in the previous mini-lab that display the first and last people in your list. Add a call to your new function after those statements, passing it the appropriate parameter. Test your new function by saving and reloading the web page. The output should be the first and last people, followed by the values of i from 0 to 4.
  3. Modify your function to print as many numbers as there are people in the list. To do this, use entryArray.length rather than the constant 5 as the upper bound for the loop index (where entryArray is whatever name you gave to your parameter). Now when you save and reload the web page, the output should be the first and last people, followed by the numbers from 0 to one less than the number of people in your list.

Another Example: Printing the Elements of an Array

One common use for a forloop is to step through the elements of an array. The example below is similar to the previous example, except that it has one extra line that uses the loop variable i as the array index into an address book array and writes the first five names to the web page. The expression entryArray[i] in the loop body refers to the single address record at index i in the array and entryArray[i].name refers to the person's name in that address book entry (if entryArray is the name of the array).

// display the names, each on a separate line
for (var i = 0; i < 5; i++)
    document.getElementById('dispAddresses').innerHTML +=
                    "i = " + i +
                    "; name = " + entryArray[i].name +
                    "<br />";


Exercise 2 - Stepping Through Array Elements
  1. Modify the function you created in Exercise 1 to display the index numbers and peoples' names from your address book, as in the example above (but for everyone in the address book, not just the first 5 people). Test your function.
  2. Modify the function again to display the name, address, city, state and zip for each person without displaying index numbers. In other words, each line of your output should contain all of the address information for one entry in your address book.
  3. Remove the lines in the body of your page that printed just the first and last people.
  4. Test your modifications.

Putting the Display in a Table

The output from the previous exercise is not very easy to read! We can display the address book information more neatly by using a table. However, the JavaScript code to generate a table is a bit tricky. Therefore, we have provided two incomplete functions, buildTable, and addTableRow, which together will display the list of addresses to a nicely formatted table. These two functions are included below, along with comments that describe their inputs. You will complete these functions in the exercise below.

// buildTable
// This function builds or re-builds the table whose id is
// tableId.  Each row of the table will contain an address from the
// addressArray, which must contain address book entry objects. 
function buildTable(tableId, addressArray) 
  var table = document.getElementById(tableId);

  // Clear old contents of the table (if any).
  numRows = table.rows.length;
  for (var i = 0; i < numRows; i++)

  // Add each entry in the address book to the table.

// addTableRow
// This function adds an address book entry to a new row in an existing table.
// The first parameter should be a table element (not an id!).
// The second and third parameters specify the address book entry.
function addTableRow (table, addressArray, index)
  // Which row is being added?  Depends on current # of rows in table.
  var nextRow = table.rows.length;
  var row = table.insertRow(nextRow);
  var cellNum = 0;

  // The cells in the row contain the person's name and address information.
  cell = row.insertCell(cellNum++);
  cell.innerHTML = addressArray[index].name;
  cell = row.insertCell(cellNum++);
  cell.innerHTML = addressArray[index].street;


Exercise 3 - Formatting Information in a Table
  1. Copy and paste the functions above into the head section of your Address Book web page. Be sure to keep the comments; good comments are an important component of good programs. (You do not need to keep the comments in all capital letters, which should be replaced by appropriate code.)
  2. Copy the following table tags into the body of your page:
    <table border="1" style="margin-left: auto; margin-right: auto" id="addressTable">
    This is the table element that the buildTable function will insert entries into. (The style attributes margin-left: auto; margin-right: auto center the table on the page.)
  3. Replace the "A FOR LOOP IS MISSING HERE" comment in the buildTable function with a for loop similar to that in Exercise 2. Within that loop, replace the code that modified the innerHTML attribute of the div tag with a call to the addTableRow function. Keep in mind that addTableRow takes three parameters: the table, the array containing address book information, and the index of the current array entry to add.
  4. Replace the "NEED CELLS" comment in addTableRow with statements similar to the ones that insert the name and street address into the table, but now inserting the city, state, and zip code into cells in the table.
  5. In the body of your web page, replace the call to your function from Exercises 1 and 2 with a call to the function buildTable. Load your page and check that it is working as expected.