HTML and CSS Reference
In-Depth Information
Working with Program Loops
Now that you're familiar with the properties and methods of arrays, you'll return to work-
ing on the calendar() function. So far, you've created only the header row, which displays
the calendar's month and year. The next row of the table will contain the three-letter
abbreviations of the seven days of the week, starting with Sun and continuing through
Sat . Each abbreviation needs to be placed within an element with the class name
calendar_weekdays . Using a document.write() command for each line of HTML
code, you could generate this table row with the following code:
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>”);
This code contains a lot of repetitive text. Imagine if you had to repeat essentially the
same string of code dozens, hundreds, or even thousands of times—the code would
become unmanageably long. Programmers deal with this kind of situation by creating
program loops. A program loop is a set of commands executed repeatedly until a stop-
ping condition is met. Two commonly used program loops in JavaScript are for loops
and while loops.
Exploring the for Loop
In a for loop , a variable known as a counter variable is used to track the number of
times a block of commands is run. Each time through the loop, the value of the counter
variable is increased or decreased by a set amount. When the counter variable reaches
or exceeds a specified value, the for loop stops. The general structure of a for loop is
for ( start ; continue ; update ) {
where start is an expression that sets the initial value of a counter variable, continue is
a Boolean expression that must be true for the loop to continue, update is an expression
that indicates how the value of the counter variable should change each time through the
loop, and commands are the JavaScript statements that are run for each loop.
Suppose you want to set a counter variable to range in value from 0 to 3 in increments
of 1. You could use the following expression to set the initial value of the variable:
var i = 0;
The name of the counter variable here is i , which is a common variable name often
applied in program loops. The next expression in the for loop structure defines the con-
dition under which the program loop continues. The following expression sets the loop
to continue as long as the value of the counter variable is less than 4:
i < 4;
Finally, the following update expression uses the increment operator to indicate that the
value of the counter variable increases by 1 each time through the program loop:
Search WWH ::

Custom Search