Alyce Brady, 2019, based on the previous Address Book project
Kalamazoo College, Kalamazoo, MI
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 ) { actionStatements; } // code after the loop |
Example:
for ( var i = 0; i < 10; i++ ) { output.innerHTML += "i = " + i + "<br>"; } // code after the loop |
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.
One time through a loop is called an iteration.
Here's an English description of how the different parts of the loop work:
init
expression).
test
. If the test fails, exit the loop
(in other words, go to step 6).
actionStatements
in the loop body.
step
expression).
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.
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++)
{
output.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
- In the
head
of the Art Catalog web page you created in the previous mini-lab, create another new function. This function will eventually print the contents of your art catalog, so give it a meaningful name that expresses this purpose. The function should take one parameter: the array of art catalog entries. (You could name itcatalogArray
, for example). For now, use the loop above as the body of the function. (This assumes that your page contains adiv
element with theid
"output". If you gave yourdiv
element a different id, then use that id instead.)In the
body
of the web page, locate the statements you wrote in the previous mini-lab that display the first and last entries in your list. Add a call to your new function after those statements, passing it the appropriate parameter. Note that in the call, the parameter name should be the variable you created in thebody
, which is not necessarily the same name as you used in the function.Test your new function by saving and reloading the web page. The output should be the first and last entries from before, followed by the values of i from 0 to 4.
- Modify your function to print as many numbers as there are entries in the list. To do this, use
catalogArray.length
rather than the constant 5 as the upper bound for the loop index (wherecatalogArray
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 entries, followed by the numbers from 0 to one less than the number of entries in your list.
One common use for a for
loop 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 art catalog array and displays the first five
array entries on the web page. The expression catalogArray[i]
in the loop body refers to the single catalog entry (record) at index
i
in the array (if you used catalogArray
as your
function parameter and
artist
as the attribute for artists' names).
Each time through the loop, it will refer to a different entry in the array.
// display the artist names, each on a separate line
for (var i = 0; i < 5; i++)
{
var entry = catalogArray[i];
output.innerHTML += "i = " + i + "; " + entry.artist + "<br>";
}
We could have written the loop above without introducing the new
entry
variable, in which case we would have referred to the
artist's name as catalogArray[i].artist
.
Exercise 2 - Stepping Through Array Elements
- Modify the function you created in Exercise 1 to display the index numbers and artists' names from your art catalog, as in the example above, but for every entry in the art catalog, not just the first 5 works. Test your function.
- Modify the function again to call your
toString
function for each entry, rather than just print the artist's name. Test your modifications.- Modify the function to drop the displaying of the index numbers. Test your modifications.
Remove (or comment out) the lines in the
body
of your page from the previous mini-lab that created and printed a single entry, and also the lines that printed information for just the first and last artworks. Test your modifications. Your output would look something like the following:
![]()
The output from the previous exercise is not very easy to read! We
can display the art catalog 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 artworks 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 a table created in the BODY // section of this page. Each row of the table will contain an entry // from the catalogArray, which must contain art catalog entry objects. function buildTable(theTable, catalogArray) { // Clear old contents of the table (if any). numRows = theTable.rows.length; for (var i = 0; i < numRows; i++) { // As the # of rows decreases, there is still a row 0. theTable.deleteRow(0); } // Add one entry from the art catalog to the table. // (Should be: Add each entry of the art catalog to the table.) // THE LINE BELOW SHOULD BE REPLACED WITH A // FOR LOOP THAT CALLS addTableRow REPEATEDLY addTableRow(theTable, catalogArray[0]); } //---------------- // addTableRow // This function adds an art catalog entry to a new row in the table // passed in as the first parameter. // The second parameter should be a single entry from the art catalog. function addTableRow (theTable, catalogEntry) { // Which row is being added? Depends on current # of rows in table. var nextRow = theTable.rows.length; var row = theTable.insertRow(nextRow); var cellNum = 0; // The cells in the row contain the information for one piece of artwork. cell = row.insertCell(cellNum++); cell.innerHTML = catalogEntry.artist; cell = row.insertCell(cellNum++); cell.innerHTML = catalogEntry.date; // NEED TO INSERT CELLS FOR THE OTHER FIELDS }
Exercise 3 - Formatting Information in a Table
- Copy and paste the functions above into the
head
section of your Art Catalog web page. Be sure to keep the comments; good comments are an important component of good programs.- Copy the following table tags into the
body
of your page (above your outputdiv
, for example):<table border="1" style="margin-left: auto; margin-right: auto;" id="artTable"> </table>This is the table element that thebuildTable
function will insert entries into. (Themargin-left
andmargin-right
style attributes center the table on the page.)Comment-out or replace the call to your printing function from Exercises 1 and 2 with a call to the function
buildTable
, passing it the id of the table you just created (without quotation marks) and the array you created in the previous mini-lab. (As you've seen in previous mini-labs, you can use an element's id as if it were a variable name.)Load your page and check that it is working as expected. (Given that the
buildTable
andaddTableRow
functions are incomplete, what do you expect the page to do at this point?)Replace the "... SHOULD BE REPLACED BY ..." comment in the
buildTable
function with afor
loop similar to that in Exercise 2. Within that loop, call theaddTableRow
function. What should you pass to it as parameters?Now that you have made this change, how do you expect your page to change? Load your page and check that it is working as expected.
![]()
Replace the "NEED TO INSERT CELLS" comment in
addTableRow
with statements similar to the ones that print the various elements of a single catalog entry, but now inserting them into cells in the table. As with printing, you will want to insert the string returned by theimageString
function into the table, rather than the plain URL.Load your page and check that it is working as expected.
You may look at the page on grading criteria for Mini-Labs 7 - 8 to see the breakdown of points given for this and the previous mini-lab.