What We Will Cover
Elucidations
Homework Questions?
Homework Discussion Questions
- How many students have worked with timed events with other programming languages?
- How does JavaScript differ from those languages? How is it similar?
- How can working with timed events provide users with a more enjoyable experience to a Web site?
- Can you think of ways that timed events could be over used?
- How many students have had to use mathematical operations in developing a Web site?
- How often is there a need to work with the more advanced math methods such as
Math.atan2() or Math.asin()?
- How do you think you could utilize the Math.random() method in a Web site to create a dynamic effect?
^ top
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
|
^ top
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

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
^ top
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:
- Create a link to the calendar CSS file:
<link href="calendar.css" rel="stylesheet" type="text/css" />
- Create a link to the JavaScript file:
<script src="calendar.js" type="text/javascript"></script>
- 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>");
}
|
^ top
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
^ top
6.1.4: Creating and Populating an Array
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
^ top
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()
^ top
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
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
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
^ top
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
- What is an array?
- What are the three ways you can declare and initialize an array?
- What statement would you use to create an array named
dayNames?
- 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"?
- What expression would you use to return the third value from the array
dayNames?
- What statement would you use to sort the
dayNames array in alphabetical order?
^ top
Activity 6.1
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
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
|
^ top
6.2.1: About Programming Loops
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
^ top
6.2.2: The for Loop
Execution Sequence
- When the
for loop is reached, execute the initialization statement
- Check if
condition is true
- if
true then continue with Step 3
- Otherwise, continue with Step 6
- Execute the statements inside the curly braces
- When end of loop body is reached, execute the
iteration statement
- Return to Step 2
- Loop is finished: continue with statements after the loop
Using the for Loop
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
^ top
6.2.3: Arrays and for Loops
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>");
}
|
^ top
6.2.4: The while Loop
Diagram of while Loop Operation

Using the while Loop
^ top
6.2.5: The do-while Loop
Using the do-while Loop
^ top
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
^ top
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
- What is a loop?
- What is the purpose of a loop test condition?
- 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?
- 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.
^ top
Activity 6.2
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
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
|
^ top
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:

- 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
^ top
6.3.2: The if Statement
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
^ top
6.3.3: Nesting if Statements
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
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];
}
|
^ top
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
- Otherwise it is false
- 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
^ top
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
^ top
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
- What is a conditional statement?
- What are the two possible values to which a test condition must evaluate?
- What is the effect of having an
if statement nested in an if statement?
- What is the effect of having an
if statement nested in an else clause?
- When does an AND (
&&) of two or more conditions evaluate to true?
- When does an OR (
||) of two or more conditions evaluate to false?
- What is the effect of the NOT (
!) operator?
^ top
Activity 6.3
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
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
|
^ top
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:
- Calculating the day of the week in which the month starts
- Preceding first day of month with blank table cells
- 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
- 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

^ top
6.4.2: Creating the writeCalDays() Function
Placing the First Day of the Month
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> </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
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> </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();
}
}
|
^ top
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
^ top
6.4.4: The switch Statement
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
^ top
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
^ top
6.4.6: Summary
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
- What is the syntax of a
switch statement?
- What are the advantages and disadvantages of using a
switch statement?
- See Session 3.3 Quick Check on page JVS 142 of the textbook for additional questions
^ top
Activity 6.4
Take one minute to review the Check Yourself questions. We will discuss the questions as time permits.
^ top
Wrap Up
Due Next: A6: Arrays, Loops and Conditions (10/16/06)
Discussion 5 and Quiz 5 (10/16/06)
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 26 2006 @20:35:45
|