6. Arrays, Loops and Conditional Statements

What We Will Cover


Elucidations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. How many students have worked with timed events with other programming languages?
  2. How does JavaScript differ from those languages? How is it similar?
  3. How can working with timed events provide users with a more enjoyable experience to a Web site?
  4. Can you think of ways that timed events could be over used?
  5. How many students have had to use mathematical operations in developing a Web site?
  6. How often is there a need to work with the more advanced math methods such as Math.atan2() or Math.asin()?
  7. How do you think you could utilize the Math.random() method in a Web site to create a dynamic effect?

6.1: Working with Arrays

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create an array
  • Populate and reference values from an array
  • Work with array methods

6.1.1: Case Study: The Chamberlain Civic Center

  • We are going to start this lesson learning about arrays
  • To help us learn, the textbook presents a case study on page JVS 101
  • You can see the design of the web site here: The Chamberlain Civic Center
  • Our job is to add a calendar at the top of the home page
  • The calendar lets visitors see which day each event is held
  • However, we do not want to manually construct a calendar
  • Instead, we are going to use JavaScript to automatically display a monthly calendar for the current date

Program Requirements

  • The overall goal is to make the calendar easily usable on other Web pages
  • Accessing and displaying the monthly calendar table should require minimal amount of coding
  • Thus, we put the JavaScript code for calendar in an external file named calendar.js
  • Also, we want to run calendar.js by calling a single function

Calendar Design

Monthly calendar design

Calendar Style Sheet

  • The calendar will be constructed as an HTML table
  • The plan is to control the look of the calendar using CSS
  • Styles are defined for us already in the file: calendar.css:
    • The id of the calendar table is: calendar_table
    • The cell containing the calendar title has the id: calendar_head
    • Seven cells containing days of week abbreviations belong to the class: calendar_weekdays
    • Cells containing dates of a month belong to the class: calendar_dates
    • The cell containing the current date has the id: calendar_today

Putting the First Pieces Together

6.1.2: Designing the calendar() Function

  • We want to make it easy to add the calendar to any web page
  • Thus, we will ask a web designer to call just one main function named calendar()
  • All a web designer needs to do to add a calendar to a page is:
    1. Create a link to the calendar CSS file:

      <link href="calendar.css" rel="stylesheet" type="text/css" />

    2. Create a link to the JavaScript file:

      <script src="calendar.js" type="text/javascript"></script>

    3. Call the calendar() function wherever you want the calendar to appear:

      <script type="text/javascript">
        calendar();
      </script>

  • The main tasks we want the calendar() function to do is:
    • Create the table header row
    • Create the table row containing the names of the days of the week
    • Create the rows containing the days of the month
  • To get started with our calendar() function, we write the opening and closing table tags
    • This is known as a function stub
    • A function stub contains just enough code to act as a placeholder
  • Before we add more functionality, we need to discuss arrays

First Version of the calendar() Function

1
2
3
4
function calendar() {
    document.write("<table id='calendar_table'>");
    document.write("</table>");
}

6.1.3: Introduction to Arrays

  • An array is a collection of data values organized using a single name
  • Since we are starting with a one-dimensional array, you can think of an array as a list of data values
  • Each data value has a number, or index, to distinguishes it from other values in the array
  • Each data value (element) of an array is identified by its name and number like this:
    arrayName[index]
  • For example, we might have an array of the names of the days of the week like the following:
    Element Value
    dayName[0] "Sunday"
    dayName[1] "Monday"
    dayName[2] "Tuesday"
    dayName[3] "Wednesday"
    dayName[4] "Thursday"
    dayName[5] "Friday"
    dayName[6] "Saturday"

Why Do We Need Arrays?

  • Arrays are very useful in JavaScript programming
  • An array is like a little database holding information
  • Once the array is populated with the data, extracting the data is easy
    • A variable name and a number like: dayName[1]
  • You could use individual variables for all the data
  • However, this get cumbersome quite quickly
  • Imagine keeping track of test scores for an exam
  • Keeping scores for 5 students in 5 different variables is OK, but what about 100 or 1000 students?
    • How would you name all the variables?
    • How would you add the scores up for all the students?
  • Anytime you have more than two or three variables of the same thing, it is usually better to store the data in an array
  • We will see later in this lesson how we can process array data using loops
  • Using a loop, you can do more with arrays than you can with individual variables

6.1.4: Creating and Populating an Array

  • To create an array:
    var arrayName = new Array(length);
  • Where arrayName is any valid variable name and length is the number of items in the array
  • For example:
    var dayNames = new Array(7);
  • The maximum length allowed for an array is 4,294,967,295 elements
  • The length is optional and the array size defaults to one (1) if it is not specified
  • The size of the array is not a large concern in JavaScript because you can increase the array size as needed
  • Specifying the number of elements makes less work for the computer
  • Thus, you should specify the number of elements if you know to speed up the processing

Populating an Array

  • Once you create an array, you can assign values using the assignment operator:
    arrayName[index] = value;
  • For example, to assign all the values to dayNames:
    dayNames[0] = "Sunday";
    dayNames[1] = "Monday";
    dayNames[2] = "Tuesday";
    dayNames[3] = "Wednesday";
    dayNames[4] = "Thursday";
    dayNames[5] = "Friday";
    dayNames[6] = "Saturday";
    
  • Note that array indexes start at 0

Creating and Populating an Array in One Statement

  • You can declare and initialize an array in one step
  • The syntax is:
    var arrayName = new Array(valuesList);
  • Where the valuesList is a list of values separated by commas
  • For example, to assign all the values to dayNames:

    var dayName = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

  • JavaScript counts the number of array elements and creates an array of the correct size
  • Then JavaScript assigns each element in the list to the array in order starting at index 0
  • Another way to create and populate an array in one statement is to use an array literal
  • The syntax is:
    var arrayName = [valuesList];
  • For example, to assign all the values to dayNames:

    var dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

  • This last form, while requiring less typing, is not supported in some older browsers
  • Thus it is customary to use one of the previous techniques to create and populate arrays

6.1.5: Creating the Calendar Title

  • Let us use what we have learned about arrays to write the title of our calendar
  • We will create a a separate function named writeCalTitle()
  • Inside the function, we start by creating and populating the array
    function writeCalTitle() {
        var monthName = new Array("January", "February",
            "March", "April", "May", "June", "July",
            "August", "September", "October", "November",
            "December");
    }
    
  • Recall that a Date object will return the number of the month
    var dateNow = new Date();
    var month = dateNow.getMonth();
    
  • Also recall that getMonth() returns a value starting with 0 for January
  • This makes it easy to use getMonth() as the index of the monthName array
  • You can see the completed function below

Function writeCalTitle()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function writeCalTitle(calendarDay) {
    var monthName = new Array("January", "February",
        "March", "April", "May", "June", "July",
        "August", "September", "October", "November",
        "December");

    var month = calendarDay.getMonth();
    var year = calendarDay.getFullYear();

    document.write("<tr>"
        + "<th id='calendar_head' colspan='7'>"
        + monthName[month]
        + "</th></tr>");
}

Calling writeCalTitle()

  • We call writeCalTitle() from the calendar() function
    function calendar() {
        var calDate = new Date();
    
        document.write("<table id='calendar_table'>");
        writeCalTitle(calDate);
        document.write("</table>");
    }
    
  • Since we need a Date object for writeCalTitle(), we create one
  • You can see the calendar with these functions at the link: ccc1.htm

6.1.6: Working with Arrays

  • Let us look at a few more capabilities of arrays that make them useful
  • An array is an object and has several properties and methods associated with it like the Date object
  • You can see a list of Array methods at: Core JavaScript 1.5 Reference:Global Objects:Array
  • We will look at some of the more commonly used methods below

Working with Array Length

  • JavaScript arrays can change size as you use them, unlike some other languages
  • Also, you do not need to define a value for every item
  • Sparse arrays: arrays with several missing or null items
  • To determine the size of an array, you can use the length property:
    arrayName.length
  • For example:
    <script type="text/javascript">
      var names = Array("Alice" , "Bob", "Charlie");
      document.write(names.length);
    </script>
    
  • Produces the output:

Reversing an Array

  • You can reverse the order of array items after the array is created using:
    arrayName.reverse()
  • For example:
    <script type="text/javascript">
      var names = Array("Alice", "Bob", "Charlie");
      document.write(names);
      document.write("<br />Reversing the array:<br />");
      names.reverse();
      document.write(names);
    </script>
    
  • Produces the output:

Sorting an Array

  • You can arrange the array items in sorted order using:
    arrayName.sort()
  • For example:
    <script type="text/javascript">
      var names = Array("Charlie", "Alice", "Bob");
      document.write(names);
      document.write("<br />Sorting the array:<br />");
      names.sort();
      document.write(names);
    </script>
    
  • Produces the output:

Methods to Extract and Insert Array Items

Method Description
push() Adds one or more elements to the end of an array
pop() Removes and returns the last element of an array
unshift() Adds one or more elements to the beginning of an array
shift() Removes the first element from an array
slice() Extracts items from the middle of an array
splice() General purpose method to insert items into or extract items from an array

Other Array Methods

6.1.7: Summary

  • In this section, we looked at how to work with arrays
  • An array is a collection of data values organized using a single name
  • To create an array you use the syntax:
    var arrayName = new Array(length);
  • Where arrayName is any valid variable name and length is the number of items in the array
  • Once you create an array, you can assign values using the assignment operator:
    arrayName[index] = value;
  • You can declare and initialize an array in one step using:
    var arrayName = new Array(valuesList);
  • Where the valuesList is a list of values separated by commas
  • Another way to create and populate an array in one statement is to use an array literal:
    var arrayName = [valuesList];
  • JavaScript arrays can change size as you use them, unlike some other languages
  • Also, you do not need to define a value for every item
  • To determine the size of an array, you can use the length property:
    arrayName.length
  • You can reverse the order of array items after array is created using:
    arrayName.reverse()
  • You can arrange the array items in sorted order using:
    arrayName.sort()
  • You can use several other methods and properties as well
  • We applied our knowledge of arrays to set up the first parts of an online calendar

Check Yourself

  1. What is an array?
  2. What are the three ways you can declare and initialize an array?
  3. What statement would you use to create an array named dayNames?
  4. What statements would you use to create an array named dayNames and initialize it with the abbreviations for the days of the week, starting with "Sun" and going through "Sat"?
  5. What expression would you use to return the third value from the array dayNames?
  6. What statement would you use to sort the dayNames array in alphabetical order?

Activity 6.1

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. In an array, each individual data value has a number or that distinguishes it from other values in the array.
  2. Given the code var thisData = new Array(5), you are telling the computer that you need __ elements.
    1. 0
    2. 1
    3. 4
    4. 5

  3. The only action you cannot perform on an array is:
    1. Sort the elements in it
    2. Remove an element
    3. Add an element
    4. All of these are possible

  4. The syntax arrayName.length() where arrayName is the name of the array, is a method that increases the number of elements in an array.

    True
    False

6.2: Working with Loops

Learner Outcomes

At the end of the lesson the student will be able to:

  • Work with for loops
  • Work with while loops
  • Loop through the contents of an array

6.2.1: About Programming Loops

  • So far our calendar() function writes only the table tags and the title
    function calendar() {
        var calDate = new Date();
    
        document.write("<table id='calendar_table'>");
        writeCalTitle(calDate);
        document.write("</table>");
    }
    
  • The next step is to write the days of the week after the title
  • One way to do this is like the following code:
document.write("<tr>");
document.write("<th class-'calendar_weekdays'>Sun</th>");
document.write("<th class-'calendar_weekdays'>Mon</th>");
document.write("<th class-'calendar_weekdays'>Tue</th>");
document.write("<th class-'calendar_weekdays'>Wed</th>");
document.write("<th class-'calendar_weekdays'>Thu</th>");
document.write("<th class-'calendar_weekdays'>Fri</th>");
document.write("<th class-'calendar_weekdays'>Sat</th>");
document.write("</tr>");
  • Note that this code contains a lot of repeated text
  • It may not seem so bad for only seven items, but what if you needed to repeat hundreds or thousands of items?
  • The code would become so long it would be unmanageable
  • Programmers deal with this type of situation using loops
  • A loop is a set of statements that are executed repeatedly
  • JavaScript has three general-purpose loops:
    for
    while
    do-while
    
  • We will start with the for loop statement

6.2.2: The for Loop

  • The for statement provides a general-purpose loop
  • Syntax:
    for (initialization; condition; iteration) {
       statements to repeat
    }
    
  • initialization: a statement that defines the initial conditions of the loop
  • condition: an expression that determines when to continue (or end) the loop
  • iteration: a statement evaluated at the end of each loop iteration
  • The statements to repeat are enclosed in the curly brackets

Execution Sequence

  1. When the for loop is reached, execute the initialization statement
  2. Check if condition is true
    • if true then continue with Step 3
    • Otherwise, continue with Step 6
  3. Execute the statements inside the curly braces
  4. When end of loop body is reached, execute the iteration statement
  5. Return to Step 2
  6. Loop is finished: continue with statements after the loop

Using the for Loop

  • A common use of a for loop is to count
  • You use a counter variable to track number of times to run the block of statements
  • For example:
    <script type="text/javascript">
      for (var count = 0; count < 5; count++) {
          document.write(count + "<br />");
      }
    </script>
    
  • Produces the output:

  • You can use a counting loop like this to repeat a block of code a certain number of times
  • Note that the iteration statement is not limited to increasing the counter by one

Check Yourself

  • Lets check our understanding of the for loop with the following code
  • Write down what you think the program will display before you check the answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Testing JavaScript for Loop</title>
  </head>

  <body>
  <script type="text/javascript">
    document.write("First loop:<br />");
    for (var count = 0; count < 5; count++) {
        document.write(count + "<br />");
    }
    document.write("Second loop:<br />");
    for (var count = 5; count > 0; count--) {
        document.write(count + "<br />");
    }
    document.write("Third loop:<br />");
    for (var i = 0; i <= 360; i += 60) {
        document.write(i + "<br />");
    }
    document.write("Fourth loop:<br />");
    for (var i = 1; i <= 64; i *= 2) {
        document.write(i + "<br />");
    }
  </script>
  </body>
</html>
Check answer

About those Curly Braces

  • Technically, the a loop statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the block
  • Curly braces are not always required, but the best practice is to always include them

6.2.3: Arrays and for Loops

  • A for loop is often used to cycle through every value in an array
  • General structure for accessing each value in array:
    for (var i = 0; i < arrayName.length; i++) {
       statements involving arrayName[i]
    }
    
  • Where arrayName is the array with the values and i is the counter variable
  • Since the last item in the array has an index of one less than the array length, the loop condition use a less-than operator

Displaying the Days of the Week

  • Using this structure, let us create a function that uses arrays and loops to create a table row displaying the names of the seven days of the week
  • First we create an array containing the three-letter abbreviations of each day:

    var dayName = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

  • Then we loop through the values of the array and display each value in a header cell:
    document.write("<tr>");
    for (var i = 0; i < dayName.length; i++) {
      document.write("<th class='calendar_weekdays'>"
          + dayName[i] + "</th>");
    }
    document.write("</tr>");
    
  • We put all this in a function named writeDayNames()
  • We then call the function from calendar()

Function writeDayNames()

1
2
3
4
5
6
7
8
9
10
function writeDayNames() {
    var dayName = new Array("Sun", "Mon", "Tue",
        "Wed", "Thu", "Fri", "Sat");
    document.write("<tr>");
    for (var i = 0; i < dayName.length; i++) {
      document.write("<th class='calendar_weekdays'>"
          + dayName[i] + "</th>");
    }
    document.write("</tr>");
}

Function calendar() with writeDayNames() Added

1
2
3
4
5
6
7
8
function calendar() {
    var calDate = new Date();

    document.write("<table id='calendar_table'>");
    writeCalTitle(calDate);
    writeDayNames();
    document.write("</table>");
}

6.2.4: The while Loop

  • The for loop is only one way of creating a loop in JavaScript
  • Let us look at the other general-purpose loops before we continue writing the calendar() function
  • The while loop is the simplest loop statement with the syntax:
    while (condition) {
        statements to repeat
    }
    
  • The loop continues as long as the condition evaluates to true
  • The condition is checked before each time through the loop, just like the for loop
  • You can see the flow in the following diagram

Diagram of while Loop Operation

While flow chart

Using the while Loop

  • You can use a while loop to count, with a counter variable, similar to a for loop
  • Here is the same example but using a while loop:
    <script type="text/javascript">
      var count = 0;
      while (count < 5) {
          document.write(count + "<br />");
          count++;
      }
    </script>
    
  • Produces the output:

  • By adding in the missing features of the for loop (initialization and iteration), you can use a while loop anywhere you use a for loop
  • In practice, you generally use for loops when you have a counter variable and a while loop for conditions that do not use counters

6.2.5: The do-while Loop

  • A variation on the while loop is the do-while loop
  • The difference between the two loops is where the condition is checked
  • In the do-while loop, the condition is checked at the end of the loop block
  • Syntax:
    do {
        statements to repeat
    } while (condition);
    
  • The loop continues as long as the condition evaluates to true

Using the do-while Loop

  • You can use a do-while loop to count, with a counter variable, similar to a while loop
  • Here is the same example but using a do-while loop:
    <script type="text/javascript">
      var count = 0;
      do {
          document.write(count + "<br />");
          count++;
      } while (count < 5);
    </script>
    
  • Produces the output:

  • By adding the necessary code, you can use any of the general-purpose loops in place of another
  • In practice, you use a do-while loop in place of a while loop when you want to ensure that the loop block runs at least once

6.2.6: Nested Loops

  • Before finishing with loops, let me mention that you can nest loops
  • Any loop statement can be nested inside the loop block of another loop
  • As an example, let us use a nested loop to create a table:
    <script type="text/javascript">
        document.write("<table border=\"1\">");
        for (var row = 1; row <= 3; row++) {
            document.write("<tr>");
            for (var col = 1; col <= 4; col++) {
                document.write("<td>");
                document.write(col + "," + row);
                document.write("<\/td>");
            }
            document.write("<\/tr>");
        }
        document.write("<\/table>");
    </script>
    
  • Produces the output:


  • Note the use of the \ as part of the closing tags
  • This is done to prevent an HTML validation problem
  • Also not that nested loops are often hard to trace
  • Thus, many programmers put the code for an inner loop in a separate function

6.2.7: Summary

  • In this section we looped at using loops in JavaScript
  • You use loops to repeat blocks of code
  • We looked at all three general-purpose loops:
    for
    while
    do-while
    
  • The syntax of the for loop is:
    for (initialization; condition; iteration) {
       statements to repeat
    }
    
  • initialization: a statement that defines the initial conditions of the loop
  • condition: an expression that determines when to continue (or end) the loop
  • iteration: a statement evaluated at the end of each loop iteration
  • The statements to repeat are enclosed in the curly brackets
  • The syntax of the while loop is:
    while (condition) {
        statements to repeat
    }
    
  • The loop continues as long as the condition evaluates to true
  • And finally, the syntax of the do-while loop is:
    do {
        statements to repeat
    } while (condition);
    
  • By adding the necessary code, you can use any of the general-purpose loops in place of another
  • In practice, you generally use for loops when you have a counter variable and a while loop for conditions that do not use counters
  • Also, you use a do-while loop in place of a while loop when you want to ensure that the loop block runs at least once
  • In addition, we discussed how you can nest a loop inside another loop
  • One of the uses of a loop is to cycle through every item in an array
  • As an example of this, we wrote the writeDayNames() function using an array and a for loop

Check Yourself

  1. What is a loop?
  2. What is the purpose of a loop test condition?
  3. What is the code for a for statement that uses a counter variable named counter that starts with the value 0 and continues up to and including 100 in increments of 10?
  4. What for statement would you code to create a table row consisting of five table cells? Assume that the table cell displays the test "Column i" where i is the value of the counter variable and that the counter variable ranges from 1 through 6.

Activity 6.2

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. When using a while loop, a command block will run for as long as a specific condition is meet.

    True
    False

  2. The do-while will run through at least ________ time(s) even if the condition is not met at the first instance:
    1. 0
    2. 1
    3. 2
    4. As many as necessary

  3. When working with a counting loop, you must always the counting variable.

6.3: Working with Conditional Statements

Learner Outcomes

At the end of the lesson the student will be able to:

  • Work with if, if...else, and multiple conditional statements

6.3.1: About Conditional Statements

  • Our next step in developing the calendar() function is to display the days of the month in table cells
  • We will start with the first day of the month and stop writing table cells and rows when we reach the last day of the month
  • To accomplish this task, we write a function to return the number of days in the month:
    function daysInMonth(calendarDay) {
       var year = calendarDay.getFullYear();
       var month = calendarDay.getMonth();
       var numDays = new Array(31, 28, 31, 30, 31, 30,
                               31, 31, 30, 31, 30, 31);
       return numDays[month];
    }
    
  • However, we have a problem: February sometimes has 29 days and not 28
  • We need to determine which year is a leap year and add one more day to February in those years
  • You can see the process for determining a leap year in the following flow chart:

Calculating a leap year

  • For our daysInMonth() function, we need to look at the year value and then decide whether to set February to have 28 or 29 days
  • We can make this decision using a conditional statement

6.3.2: The if Statement

  • A conditional statement runs a block of commands only when certain conditions are met
  • The most commonly used conditional statement is the if statement
  • Syntax:
    if (condition) {
        statements to execute
    }
    
  • The statements inside the block execute only if the condition evaluates to true
  • For example:
    if (year == 2008) {
        numDays[1] = 29;
    }
    

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the block
  • Curly braces are not always required, but the best practice is to always include them

Modulus Operator

  • We need a general way to determine if a year is divisible by 4
  • One way is to use the modulus operator
  • The modulus operator returns the integer remainder after dividing one integer by another
  • For example:
    2009 % 4
    returns the value 1 because 1 is the remainder after dividing 2009 by 4
  • To test whether a calendar year is divisible by 4, we can use the expression:
    (year % 4 == 0)
    where year contains the four-digit year value
  • Applying this condition to an if statement we have:
    if (year % 4 == 0) {
        numDays[1] = 29;
    }
    

6.3.3: Nesting if Statements

  • Our previous if-statement is only an approximation of how to adjust for leap years
  • It is not completely accurate because if does not take into account century years
  • We need to include a second test to use a different rule during century years
  • We can do this by nesting if statements
    if (year % 4 == 0) {
        // if statement for century years
    }
    
  • We need two conditions for our nested if statement:
    1. the year is not divisible by 100, or
    2. the year is divisible by 400
  • If either condition is true, then the year is a leap year
  • We can express these two conditions as:
    1. (year % 100 != 0)
    2. (year % 400 == 0)
  • However, we still need to join the two conditions in some logical manner
  • To join these conditions, we can use a logical operator

Logical Operators

Operator Description Example Value
&& Returns true when both expressions are true (AND) var x = 20, y = 25;
var z = (x == 20) && (y == 25);
document.write(z);
true
|| Returns true then either expression is true (OR) var x = 20, y = 25;
var z = (x == 20) || (y == 10);
document.write(z);
true
! Reverses the truth value (NOT) var x = 20, y = 25;
var z = !(x == 20);
document.write(z);
false

Finishing the daysInMonth() Function

  • For our application we need to use the OR operator
    • Spelled || in JavaScript
  • Thus we combine the two expressions and come up with:
    ((year % 100 != 0) || (year % 400 == 0))
    
  • The complete daysInMonth() function is shown below
1
2
3
4
5
6
7
8
9
10
11
12
function daysInMonth(calendarDay) {
    var year = calendarDay.getFullYear();
    var month = calendarDay.getMonth();
    var numDays = new Array(31, 28, 31, 30, 31, 30,
                            31, 31, 30, 31, 30, 31);
    if (year % 4 == 0) {
        if ((year % 100 !=0) || (year % 400 == 0)) {
            dayCount[1] = 29; // leap year
        }
    }
    return numDays[month];
}

6.3.4: The if-else Statement

  • The if statement executes a block of commands only if the conditional expression evaluates to true
  • It does nothing if the conditional expression evaluates to false
  • Sometimes we want to do something so we can choose between two actions
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • General syntax:
    if (condition) { // evaluates to true
        execute statements only if true
    } else {
        execute statements only if false
    }
    
  • For example:
    <script type="text/javascript">
      var day = "Monday";
      if (day == "Friday") {
          document.write("TGIF!");
      } else {
          document.write("Today is " + day);
      }
    </script>
    
  • Produces the output:


  • Note that there is no test condition for the else clause
  • The decision on which set of statements to use depends on only one condition
  • For clarity, you write the if and else on different lines than the other statements
  • Also, you indent the command blocks as shown

6.3.5: Multiple else-if Statements

  • Sometimes you may need to test between several alternatives
  • In these cases, you can specify multiple else clauses with its own if statement
  • General structure:
    if (condition 1) {
        statements for first condition
    } else if (condition 2) {
        statements for second condition
    } else if (condition 3) {
        statements for third condition
    }
    ...
    } else {
        statements for default case
    }
    
  • For example:
    <script type="text/javascript">
      var day = "Monday";
      if (day == "Friday") {
          document.write("TGIF!");
      } else if (day == "Monday") {
          document.write("Blue Monday");
      } else if (day == "Saturday") {
          document.write("Sleep in today");
      } else {
          document.write("Today is " + day);
      }
    </script>
    
  • Produces the output:


  • Note the indentation and position of the curly braces

6.3.6: Summary

  • In this section we looked at conditional statements
  • You use conditional statements when you want to make a choice between various options
  • The most commonly used conditional statement is the if statement, which has the syntax:
    if (condition) {
        statements to execute
    }
    
  • The statements inside the curly braces execute only if the condition evaluates to true
  • To chose between two actions, you use an if-else statement:
    if (condition) { // evaluates to true
        // execute statements only if true
    } else {
        // execute statements only if false
    }
    
  • When you want to test between several alternatives, you can use multiple else-if statements of the form:
    if (condition 1) {
        statements for first condition
    } else if (condition 2) {
        statements for second condition
    } else if (condition 3) {
        statements for third condition
    }
    ...
    } else {
        statements for default case
    }
    

Check Yourself

  1. What is a conditional statement?
  2. What are the two possible values to which a test condition must evaluate?
  3. What is the effect of having an if statement nested in an if statement?
  4. What is the effect of having an if statement nested in an else clause?
  5. When does an AND (&&) of two or more conditions evaluate to true?
  6. When does an OR (||) of two or more conditions evaluate to false?
  7. What is the effect of the NOT (!) operator?

Activity 6.3

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. The expression 9 % 8 returns the value .
  2. You may nest ________ else-if statement(s) in a JavaScript program:
    1. 0
    2. 1
    3. 2
    4. As many as necessary

  3. The else statement is the default conditional selected when all possible conditions are not met.

    True
    False

6.4: More Control Statements

Learner Outcomes

At the end of the lesson the student will be able to:

  • Use arrays, loops, and conditional statements to create a table
  • Work with break and continue statements

6.4.1: Completing the calendar() Function

  • Let us apply all we have learned about arrays, loops and conditional statements to finish the calendar() function
  • Note that this is an important part in your development as a JavaScript programmer
  • Much of the programs written in JavaScript rely heavily on the use of arrays, loops, and conditional statements

The Plan

  • So far we have written the code for writing the calendar title and the days of the week
  • Now we need to write the actual calendar dates, which involves:
    1. Calculating the day of the week in which the month starts
    2. Preceding first day of month with blank table cells
    3. Looping through days of the month while:
      • Writing each date in a different table cell
      • Starting a new table row on each Sunday
      • Ending the table rows after each Saturday
    4. Highlighting current date in calendar
  • The following diagram from the textbook shows the steps needed to finish the calendar
  • We will place the code for these steps in a function named writeCalDays()
  • The function will have a single parameter of a type Date that specifies the calendar date

Building the Monthly Calendar

Calendar table steps

6.4.2: Creating the writeCalDays() Function

  • Our first task is to calculate the day of the week in which the month starts
  • This is straightforward because the Date object has a getDay() method
  • This method returns the day of the week for the specified date
  • Thus, our first version of the function is:
    function writeCalDays(calendarDay) {
        calendarDay.setDate(1);
        var weekDay = calendarDay.getDay();
    }
    

Placing the First Day of the Month

  • Prior to the first day of the month, our table should show only empty cells
  • The variable weekDay tells us how many empty cells to write
  • All we need to do now is use a counting loop to write the required number of cells
  • Adding this to our function gives us the code:
    function writeCalDays(calendarDay) {
        calendarDay.setDate(1);
        var weekDay = calendarDay.getDay();
    
        document.write("<tr>");
        for (var i = 0; i < weekDay; i++) {
            document.write("<td></td>");
        }
    }
    

Writing the Calendar Days

  • Once we have written all the blank cells we need to write the cells for each day of the month
  • This will need a loop like the following:
    var dayCount = 1;
    var totalDays = daysInMonth(calendarDay);
    
    while (dayCount <= totalDays) {
        // write the table rows and cells
        // move to the next day
    }
    
  • Each new table row in the calendar table starts with a Sunday
  • Thus, the first thing to check is if the weekDay is a Sunday
    if (weekDay == 0) {
        document.write("<tr>");
    }
    
  • We need to write the day of the month in its own cell using code like:

    document.write("<td class='calendar_dates'>" + dayCount + "</td>");

  • Each table row ends on a Saturday, so we need to check for the end of the week using:
    if (weekDay == 6) {
        document.write("</tr>");
    }
    
  • To end our loop, we need to update the values of dayCount, calendarDay and weekDay:
    dayCount++;
    calendarDay.setDate(dayCount);
    weekDay = calendarDay.getDay();
    
  • Adding all this to our function gives us the code:
    function writeCalDays(calendarDay) {
        var dayCount = 1;
        var totalDays = daysInMonth(calendarDay);
        calendarDay.setDate(1);
        var weekDay = calendarDay.getDay();
    
        document.write("<tr>");
        for (var i = 0; i < weekDay; i++) {
            document.write("<td>&nbsp;</td>");
        }
    
        while (dayCount <= totalDays) {
            if (weekDay == 0) {
                document.write("<tr>\n");
            }
    
            document.write("<td class='calendar_dates'>"
                + dayCount + "</td>\n");
    
            if (weekDay == 6) {
                document.write("</tr>\n");
            }
    
            dayCount++;
            calendarDay.setDate(dayCount);
            weekDay = calendarDay.getDay();
        }
    }
    

Highlighting the Current Date

  • We still need to highlight the current date on the calendar
  • To highlight the current date, we will write the table cell with a different style
  • We will apply the style using: id='calendar_today'
  • As we loop through the each day in the calendar, we need to decide whether the day being written is the original calendarDay
  • To do this, we first need to save the current day before we start modifying the calendarDay:
    var currentDay = calendarDay.getDate();
    
  • Then we need to test whether dayCount is equal to the currentDay
  • You can see the completed code for writeCalDays() below

Completed writeCalDays() Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function writeCalDays(calendarDay) {
    var currentDay = calendarDay.getDate();

    var dayCount = 1;
    var totalDays = daysInMonth(calendarDay);
    calendarDay.setDate(1);
    var weekDay = calendarDay.getDay();

    document.write("<tr>");
    for (var i = 0; i < weekDay; i++) {
        document.write("<td>&nbsp;</td>");
    }

    while (dayCount <= totalDays) {
        if (weekDay == 0) {
            document.write("<tr>\n");
        }

        document.write("<td class='calendar_dates'");
        if (dayCount == currentDay) {
            document.write(" id='calendar_today'>"
                + dayCount + "</td>\n");
        } else {
            document.write(">"
                + dayCount + "</td>\n");
        }

        if (weekDay == 6) {
            document.write("</tr>\n");
        }

        dayCount++;
        calendarDay.setDate(dayCount);
        weekDay = calendarDay.getDay();
    }
}

6.4.3: The Final calendar() Function

  • With the writeCalDays() function completed, we need to write the final calendar() function
  • The customer requests a change to the specification to include a parameter for the calendar() function
    • Customers often change the specification as a project progresses
    • As a professional, you try to accommodate the changes when feasible
  • The customer wants the calendar() function to work like new Date()
  • If a parameter is included then a calendar is created for the specified month
  • Otherwise, a calendar is created for the current month
  • We can create this code using an if statement and a test for null like this:
    function calendar(calendarDay) {
        if (calendarDay == null) {
            calendarDay = new Date();
        }
    // more code here
    
  • This allows us to call the calendar() function either like this:
    calendar()
    or like this:
    calendar("November 13, 2006")
  • The final calendar function is shown below
  • Also, you can see the final web site, with the calendar, at: The Chamberlain Civic Center

Completed calendar() Function

1
2
3
4
5
6
7
8
9
10
11
12
13
function calendar(calendarDay) {
    if (calendarDay == null) {
        calDate = new Date();
    } else {
        calDate = new Date(calendarDay);
    }

    document.write("<table id='calendar_table'>");
    writeCalTitle(calDate);
    writeDayNames();
    writeCalDays(calDate);
    document.write("</table>");
}
  • To finish our study of loops and conditional statements, we should look at another couple of statements
  • Note that these statements do not add any new capabilities to JavaScript
  • However, they are used and you need to understand them

6.4.4: The switch Statement

  • The switch statement provides an alternative to multiple else-if statements
  • Executes a section of code depending on value of a variable
  • General form:
    switch (expression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
    }
    
  • The keyword switch identifies the start of the switch statement
  • The expression is evaluated for comparison to each case label
  • Within a switch statement, keyword case labels each entry point into the code
    • Code executes if expression matches the case label value
    • Execution starts with the statement immediately following the match
  • Any number of case labels can be placed in any order
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

Example Using the switch Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript">
  var day = "Monday";
  switch (day) {
      case "Friday":
          document.write("TGIF!");
          break;
      case "Monday":
          document.write("Blue Monday");
          break;
      case "Saturday":
          document.write("Sleep in today");
          break;
      default:
          document.write("Today is " + day);
  }
</script>
Produces the output:

Compare this to using multiple else-if statements:
1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
  var day = "Monday";
  if (day == "Friday") {
      document.write("TGIF!");
  } else if (day == "Monday") {
      document.write("Blue Monday");
  } else if (day == "Saturday") {
      document.write("Sleep in today");
  } else {
      document.write("Today is " + day);
  }
</script>

When to Use switch Statements

  • switch statements are inherently less useful than else-if statements
  • You cannot use anything but equality to match each case
  • The syntax is no clearer than else-if statements
  • Thus, you never gain anything by using a switch statement

6.4.5: The break and continue Statements

  • We saw the use of the break statement in the switch statement
  • However, you can use the break statement anywhere in your code
  • The purpose of the break statement is to terminate any program loop or conditional statement
  • The continue statement is similar except that instead of exiting a loop, it jumps to the end of the loop
  • The causes the loop to skip the rest of the current iteration and start the next iteration
  • The following code shows an example of break and continue

Example Using the break and continue Statements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type="text/javascript">
  var count = 0;
  while (true) {
      count++;
      if (count ==3) {
          continue;
      }
      document.write(count + "<br />");
      if (count >= 5) {
          break;
      }
  }
  document.write("After count=" + count);
</script>
Produces the output:

When to Use break and continue Statements

  • Use break statements in switch statements only
  • Never use break in looping constructs
    • Poor coding habit
    • Loops and conditionals should only have one exit point
  • You do not need to use continue statements either
  • You can accomplish the same operation other ways

6.4.6: Summary

  • In this section we discussed applied our knowledge of array, loops and conditional statements to create a table
  • We also discussed the switch statement, which has the syntax:
    switch (expression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
    }
    
  • Also, we discussed the break and continue statements
  • The purpose of the break statement is to terminate any program loop or conditional statement
  • The continue statement is similar except that instead of exiting a loop, it jumps to the end of the loop
  • None of these statements add any new capabilities to JavaScript
  • However, they are used and you need to understand them

Tips for Arrays, Loops and Conditional Statements

  • Save space in your program code by declaring and populating each array in a single new Array() declaration
  • Use array methods like sort() and reverse() to quickly rearrange contents of arrays
  • Use a for loop when your loop contains a counter variable
  • Use while loop for more general stopping conditions
  • To simplify your code avoid nesting too many levels of if statements
  • Avoid using break and continue statements except when using break in a switch statement
  • Instead use the conditional expression to determine when to exit a loop or conditional statement

Check Yourself

  1. What is the syntax of a switch statement?
  2. What are the advantages and disadvantages of using a switch statement?
  3. See Session 3.3 Quick Check on page JVS 142 of the textbook for additional questions

Activity 6.4

Take one minute to review the Check Yourself questions. We will discuss the questions as time permits.

Wrap Up

Due Next:
A6: Arrays, Loops and Conditions (10/16/06)
Discussion 5 and Quiz 5 (10/16/06)

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: November 26 2006 @20:35:45