CHS Web Design Track

JavaScript for Web Warriors, 7e Chapter

Chapter 3: Building Arrays and Controlling Flow

Objectives

  • Create an array containing a list of data values.
  • Access a collection of HTML elements by type.
  • View arrays and HTML collections using the browser console.
  • Create program loops using while, do while, and for loops.
  • Explore array methods to replace program loops.
  • Make decisions with if statements and switch statements.
  • Manage program loops and conditional statements with the break, continue, and label commands.

Storing Data in Arrays

Elements and indexes

  • Element: a value stored in an array
  • Index: position of an element within an array; indexes begin with 0
  • Syntax to set a specific array value by its index:
    array[index] = value;
  • JavaScript arrays are dynamic
    • They automatically expand to allow for new elements
    • Can create sparse arrays in which some values are left undefined so the length is greater than the number of defined values
    • Syntax for the property used to query an array's current size:
      array.length
Figure 3-1 Tipton Turbines game calendar
To open the Tipton Turbines web page:
  1. Use your code editor to go to the js03 c chapter folder of your data files.
  2. Open the js03_txt.html file in your code editor and enter your name and the date in the comment section of the file.
  3. Scroll through the document to familiarize yourself with its contents. Notice that the page contains a web table in which the table body consists of five rows of seven table cells with the table cell ids containing calendar dates ranging from “2024-7-28” up to “2024-8-31”.
  4. Save the file as js03.html and load the file in your browser.
To create an array of weekday names:
  1. Open the js03_txt.js file in your code editor and enter your name and the date in the comment section of the file.
  2. Directly below the comment section, enter the following code for the weekDays array as shown in Figure 3-2.
    // Days of the week
    let weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"];
  3. Save the file as js03.js.
Figure 3-2 Creating the weekDays array
Figure 3-3 Arrays describing the results of 23 games
To load the js03.js and schedule.js files into the web page:
  1. Return to the js03.html file in your code editor.
  2. Directly above the closing </head> tag, insert the following script elements:
    <script src="schedule.js" defer></script>
    <script src="js03.js" defer></script>
  3. Save your changes to the file.

Multidimensional arrays

Quick Quiz 1
  1. True or False: The numbering of elements within an array starts with the index number zero (0). (3.1)
  2. A(n) ____ is an element's numeric position within the array. (3.1) Answer: index True or False: JavaScript requires that all of the elements in an array be of the same data type. (3.1)
  3. True or False: After you have assigned a value to an array element, you can change it later. (3.1
  4. The ____ property returns the number of elements in an array. (3.1)

Exploring HTML Collections

HTML Collection Collection of
embeds <embed> elements in the document
forms <form> elements in the document
form.elements Elements within a web form
getElementsByClassName(class) Elements in the document with belonging to the class class
getElementsByName(name) Elements in the document with a name attribute equal to name
getElementsByTagName(tag) Elements in the document with a tag name equal to tag
images <img> elements in the document
links <a> elements and <area> elements with a href attribute
scripts <script> elements in the document
styleSheets Stylesheet objects associated with the document

Referencing an element within a collection

Searching through the DOM

Viewing Arrays and HTML Collections with the Console

To view arrays in your browser console:
  1. Return to the js03.html file in your web browser.
  2. Open the console using commands appropriate for your web browser. (Hint: You can view your browser's online help if you are unsure how to access the Developer Console.)
  3. Within the console type gameDates.length and press Enter. The console returns a value of 23, indicating that there 23 elements in the gameDates array for the 23 games played by the team.

    Note that the console may try to automatically complete your entry or show a list of names matching the first few characters of your entry. You can speed up the process and save yourself some typing by pressing Tab or double-clicking the name from the list provided by the console.

  4. Type gameOpponents[4] and press Enter. The console returns the text string “Clinton” which is the fifth opponent listed in the calendar shown earlier Figure 3-1.
  5. Type gameResults[4] and press Enter. The console returns the text string “L” indicating that the fifth game was a loss.

    You can also use the console to view information about the elements in your document. Use this feature now to determine the number of hypertext links in the document.

  6. Type document.links.length and press Enter. The console reports 5 links in the document.
  7. Type document.links[1].innerHTML and press Enter. The console returns the text string “Calendar”, indicating that the HTML code stored in the second text string is the word “Calendar”.

    Finally, if you attempt to retrieve a value that is undefined, the console will report that error.

  8. Type gameOpponents[23] to retrieve the opponent for a non-existent 24th game. The console returns the value undefined, indicating that there is no value matching this reference.

    Figure 3-5 shows the results of Google Chrome's console for retrieving information on arrays and HTML collections.

  9. Continue exploring arrays and collections using the console. It is a great tool for becoming more familiar with these concepts and techniques. Close the console when finished.
Figure 3-5 Information on arrays and collections viewed in the console
Quick Check 1
  1. Show how to create an array named foodMenu containing the text strings “Breakfast”, “Lunch”, and “Dinner” as an array literal and using the new Array() object constructor.
  2. Provide a command to return the size of the array customerOrders.
  3. Provide a command to return the tenth entry in the customerOrders array.
  4. Provide the expression to reference to fifth inline image in the document.
  5. Provide the expression to reference the third element belonging to the blogpost class

Working with Program Loops

The while loop

Initial ValueIterationWhile ConditionIterated Values
let i = 5i++i <= 10i = 5, 6, 7, 8, 9, 10
let i = 5i--i > 0i = 5, 4, 3, 2, 1
let i = 0i += 60i <= 180i = 0, 60, 120, 180
let i = 1i *= 2i <= 50i = 1, 2, 4, 8, 16, 32
let i = 90i /= 3i > 5i = 90, 30, 10

To create the while loop:
  1. Return to the js03.js file in your code editor.
  2. At the bottom of the file insert the following event listener to run the addWeekDays() function when the page is loaded:
    window.addEventListener("load", addWeekdays);
  3. Below this statement, add the following addWeekDays() function as described in Figure 3-7:
    // Function to write weekday names into the calendar
        function addWeekDays() {
            let i = 0; // initial counter value
            // reference the collection of heading cells
            let headingCells = document.getElementsByTagName("th");
            // write each of the seven days into a heading cell
            while (i < 7) {
            headingCells[i].innerHTML = weekDays[i];
            // increase the counter by 1
            i++;
        }
    }
  4. Save your changes to the file and then reload the js03.html file in your web browser. As shown in Figure 3-8, the calendar now includes a table row displaying the days of the week.
Figure 3-7 Creating a while loop
Figure 3-8 Adding the weekday names to the table

The do while loop

The for loop

Writing a for loop

To create the showGames() function:
  1. Return to the js03.js file in your code editor.
  2. At the bottom of the file insert an event listener to run the showGames() function when the page is loaded:
    window.addEventListener("load", showGames);
    Remember that because multiple functions can be attached to an event listener, this event listener will supplement the event listener created earlier for the addWeekDays() function.
  3. Below the event listener, add the following showGames() function as described in Figure 3-9:
    // Function to write game information into the calendar
    function showGames() {
        for (let i = 0; i < gameDates.length; i++) {
            let gameInfo = "";
            // Open the paragraph
            gameInfo += "<p>";
            // Include the opponent
            gameInfo += gameOpponents[i] + "<br>";
            // Include the result and score
            gameInfo += gameResults[i] + ": (" + runsScored[i] +
            " - " + runsAllowed[i] + ")";
            // Close the paragraph
            gameInfo += "</p>";
            // Write the information into a table cell
            let tableCell = document.getElementById(gameDates[i]);
            tableCell.insertAdjacentHTML("beforeEnd", gameInfo)
        }
    }
  4. Save your changes to the file and then reload the js03.html file in your web browser. Information on each game is added to a table cell matching the game date. See Figure 3-10.
Figure 3-9 Add information on each game to the calendar
Figure 3-10 Game data for July and August

Exploring Array Methods for Generating Loops

Array Method Description
every(callback, thisArg) Tests whether the value of the callback function is true for all array elements
filter(callback, thisArg) Creates a new array populated with the elements of the array that return a value of true from the callback function
forEach(callback, thisArg) Applies the callback function to each array element
map(callback, thisArg) Creates a new array by passing the original array elements to the callback function, which returns the mapped value of those elements
reduce(callback, thisArg) Reduces the array by keeping only those elements returning a true value from the callback function
reduceRight(callback, thisArg) Reduces the array starting from the last element by keeping only those elements returning a true value from the callback function
some(callback, thisArg) Tests whether the value of callback function is true for at least one array element
find(callback, thisArg) Returns the value of the first array element returning a true value from the callback function
findIndex(callback, thisArg) Returns the index of the first array element returning a true value from the callback function
Quick Quiz 2
  1. Each repetition of a looping statement is called a(n) ____. (3.4)
  2. In a(n) ____, a loop statement never ends because its conditional expression is never false. (3.4)
  3. The ____ statement executes a statement or set of statements once, and then repeats the execution as long as a given conditional expression evaluates to true. (3.4)
  4. True or False: The for statement is used for repeating a statement or series of statements as long as a given conditional expression evaluates to true. (3.4)
Quick Check 2
  1. Show how to use a while loop to write the HTML code <td>counter</td> for integer values of counter ranging from 1 to 100 by 1.
  2. What is the most important difference between a while loop and a do while loop?
  3. Provide code for a for loop that writes the following HTML code:
    <td>3</td> <td>6</td> <td>12</td> <td>24</td> <td>48</td><td>96</td>
  4. What JavaScript method can be used to insert HTML code just after an element's opening tag?
  5. What JavaScript method can be used to apply a function to each element of an array without writing a program loop?

Adding Decision Making to Your Code

The if statement

The if else statement

The else if statements

To create an else if statement:
  1. 1. Return to the js03.js file in your code editor and scroll down to the showGames() function.
  2. Directly after the statement that writes the opening

    tag, insert the following else if statement as shown in Figure 3-12.

    // Display the game location
    if (gameLocations[i] === "h") {
    gameInfo += "vs. ";
    } else if (gameLocations[i] === "a") {
    gameInfo += "@ ";
    }
    Note that there is no else condition in this statement because all games should be either home ("h") or away ("a") and if a different value was entered in the gameLocations array or no value at all, that situation shouldbe flagged by not displaying the “vs.” or @ characters. You should always write your code to help catch potential errors in your data.
  3. Save your changes to the file and then reload the js03.html file in your web browser. Verify that all games are listed as either home or away on the calendar (see Figure 3-13.)
Figure 3-12 Inserting an else if statement
Figure 3-13 Home and away games
To display the innings played:
  1. Return to the js03.js file in your code editor and go to the showGames() function
  2. Directly above the comment for closing the paragraph insert the following else if statement (see Figure 3-14).
    // Display innings played for suspended, shortened, or extrainning games
    if (gameInnings[i] < 5) {
    gameInfo += " [" + gameInnings[i]+"]***";
    } else if (gameInnings[i] < 9) {
    gameInfo += " [" + gameInnings[i]+"]*";
    } else if (gameInnings[i] > 9) {
    gameInfo += " [" + gameInnings[i] + "]";
    }
  3. Save your changes to the file and then reload the js03.html file in your web browser. As shown in Figure 3-15, innings are added to those games that are suspended, shortened, or go into extra innings, but games that went for nine innings are not changed.
Figure 3-14 Conditional statements based on innings played
Figure 3-15 Displaying innings played

Nested if and if else statements

Activity 3.1: Knowledge Check
  1. Characterize the following code snippet and describe what will happen when it runs.
    for (let i = 1; i < 100; i++) {
       document.write(i + “<br>”);
    }
    document.write(“<p>The value of i is equal to “ + i + “</p>”);
  2. Suppose you want your program to execute command block A if the integer value of the numberOfGuests variable is 15 or fewer, block B if its value is between 16 and 50, block C if its value is between 51 and 150, and block D if its value is 151 or more. Which decision-making structure discussed in Chapter 3 would likely be the best fit?
    An else if statement would likely be the best fit in this scenario because you could cover all four possibilities using clauses with conditional expressions containing comparison operators in an appropriate sequence. See the following slide for an example.
    Using nested if or if else statements would be more complicated, and a switch statement could not readily be used because it is based on discrete values (no comparisons).

Conditional statements and browser testing

The switch statement

  1. Return to the js03.js file in your code editor and go to the showGames() function.
  2. Replace the statement let gameInfo = "

    " that writes the paragraph's opening tag with the following switch statement that chooses one of four possible opening paragraph tags:

    switch (gameResults[i]) {
    case "W":
    gameInfo += "

    "; break; case "L": gameInfo += "

    "; break; case "S": gameInfo += "

    "; break; case "P": gameInfo += "

    "; break; }

    Figure 3-16 shows the newly added code in the function.
  3. Save your changes to the file and then reload the js03.html file in your web browser. Figure 3-17 shows the final version of the calendar.
Figure 3-16 Creating a switch statement
Figure 3-17 Final monthly calendar for the Tipton Turbines

Managing Program Loops and Conditional Statements

The break statement

The continue statement

Statement labels

Quick Quiz 3
  1. The ____ statement executes specific programming code if the evaluation of a conditional expression returns a truthy value. (3.6)
  2. An if statement that includes an additional clause that runs a different command block when the condition is not true is called a(n) ____ statement. (3.6)
  3. In a switch decision structure, if the value of the label for a _____ matches the value of the switch statement's expression, one or more statements that follow the label will execute. (3.6)
  4. The ____ label contains statements that execute when the value returned by the switch statement expression does not match a case label. (3.6)
  5. A(n) ____ statement is used to end the execution of a switch statement. (3.6)
Quick Quiz 4
  1. You use the ____ statement when you want to stop the loop for the current iteration, but want the loop to continue with a new iteration. (3.7)
Activity 3.2: Think, Pair, and Share
  1. Form pairs/groups of two to four class members.
  2. Your group will write a small program to manipulate array elements and display them on a web page. First, choose a theme for your data and write code to declare four arrays and populate them with equal numbers of elements—at least five per array. For instance, your arrays might contain text strings representing the names of flowers of four colors: red, blue, yellow, and purple.
  3. Next, write code to write the arrays to a web page as the four rows of a table using a program loop(s).
  4. Finally, add an alternate block of statements that displays the array data in an appropriate non-tabular format and a decision-making structure to your code. The decision-making structure will determine whether the program displays the array data as a table or in the other format (i.e., which of the alternate command blocks to run).
Activity 3.3: Discussion Questions
  1. What are the differences between decision-making statements and loop statements?
  2. Is it necessary to use nested decision-making statements? Explain your reasoning. In what programming situations, if any, are nested decision-making statements useful?
Self-Assessment
  1. How or in what situations do you expect that you will use JavaScript arrays to store data? If you have used arrays in other programming languages, how will your use of them in JavaScript be similar or different and why?
  2. How have you used HTML collections in web page development previously? Describe how the techniques you learned from Chapter 3 can improve or enhance your code that manipulates HTML elements.
  3. Chapter 3 demonstrated several key program control structures. Which of these were most and least familiar to you, and which do you like best? Which do you expect to rely on most often when involved in professional web development?