HTML and CSS Reference
In-Depth Information
Exploring the switch Statement
Another way to handle multiple conditions is with the switch statement —also known
as the case statement —in which different commands are run based upon different pos-
sible values of a specified variable. The syntax of the switch statement is
switch ( expression ) {
case label1 : commands1 ;
break;
case label2 : commands2 ;
break;
case label3 : commands3 ;
break;
...
default: default commands
}
where expression is an expression that returns a value; label1 , label2 , etc., are
possible values of that expression; commands1 , commands2 , etc., are the commands
associated with each label; and default commands is the set of commands to be run if
no label matches the value returned by expression . The following switch statement
demonstrates how to run a different document.write() command based on the value
of the day variable:
switch (day) {
case “Friday”: document.write(“Thank goodness it's Friday”);
break;
case “Monday”: document.write(“Blue Monday”); break;
case “Saturday”: document.write(“Sleep in today”); break;
default: document.write(“Today is “ + day);
}
The break statement is optional and is used to halt the execution of the switch state-
ment once a match has been found. For programs with multiple matching cases, you can
omit the break statements and JavaScript will continue moving through the switch
statements, running all matching commands.
Because of its simplicity, the switch statement is often preferred over a long list of
else if statements that can be confusing to read and to debug.
Completing the calendar() Function
The last part of creating the calendar involves writing table cells for each day of the
month. The completed calendar app must do the following:
• Calculate the day of the week in which the month starts.
• Write blank table cells for the days before the first day of the month.
• Loop through the days of the current month, writing each date in a different table cell
and starting a new table row on each Sunday.
You'll place all of these commands in a function named writeCalDays(). The function
will have a single parameter named calendarDay storing a Date object for the current
date. You'll add this function to the calendar.js ile.
Search WWH ::




Custom Search