JavaScript Tutorial - "for" Loops

Left
Right

So far you've just done once-through programs. The great power of computers and programming is that you can have the machine repeatedly do similar calculations over and over.

Here we start with the for loop, which is ideal for loops where you know the starting value, the ending value, and the increment to use to progress through the loop.

In the following example we will use a doubly nested loop - a loop inside another loop - to create a multiplication table. We will do this twice. The first way will use plain formatting via the <PRE> HTML tag as we have shown in previous examples.

The second multiplication table will use <TABLE> HTML formatting. This also demonstrates how JavaScript works with HTML. Just output text with the HTML formatting tags

The basic form for a for loop is:

for (initialize statement, end test, increment statement) {
	block of code ...
}

The end test is a conditional statement, which will be discussed in more detail later.

Where:

  • intialize statement - code to initialize the loop variables
  • end test - conditional such that it turns false when the loop is supposed to end. (More on conditionals later.)
  • increment statement - give the loop variables new values. Typically the ++ operator is used to increment the values by 1. You can use += to increment by some arbitrary value such as 2 (e.g. j += 2).
  • block of code ... - are the statements to execute for each iteration of the loop. Generally some expression in terms of the loop variables.

Example: work/forloop.html

<HTML>
<BODY>
<PRE>
<SCRIPT LANGUAGE="JavaScript">
// use pre-formatted output for this multiplication table
var i,j;	// loop variables

for (j=1; j<=10; j++) {
	for (i=1; i<=10; i++) {
		document.write("\t",i*j);
	}
	document.write("\n");	// end the line
}
</SCRIPT>
</PRE>
<TABLE BORDER=1 CELLPADDING=6>
<SCRIPT LANGUAGE="JavaScript">
for (j=1; j<=10; j++) {
	document.write('<TR>');
	for (i=1; i<=10; i++) {
		document.write('<TD ALIGN="RIGHT">',i*j,'</TD>');
	}
	document.write("</TR>\n");	// end the line
}
</SCRIPT>
</TABLE>
</BODY>
</HTML>

HOMEWORK:

  1. Use the functions F2C() and C2F() defined in a previous assignment and create a conversion table. Use the values 0 to 100 in increments of 2. Display the value, the Celsius conversion (F2C), and the Fahrenheit conversion (C2F).
    You can use either <PRE> or <TABLE> formatting.
Left
Right
Slide 8