Learn Java Script, Optimizing Code with Looping Logic, Lesson No. 22
A loop is a series of statements that executes repeatedly, allowing you to perform iterative operations within your script. JavaScript and JScript statements that support looping logic include the for, while, do…while, label, break, and continue statements. The nice thing about loops is that they enable you to write just a few line of code and then to execute them repeatedly, making your scripts easier to write and maintain.
The for Statement
The for statement executes until a condition becomes false and uses a variable to control the number of times the loop executes. The for loop is comprised of three parts: a starting expression, a test condition, and an increment statement. The syntax of the for statement is shown here:
for (expression; condition; increment) {
statements;
}
For example, the statement for (i=0; i<5; i++) establishes a for loop that has an initial count of 0, that runs as long as i is less than 5, and that increments the value of i by one upon each iteration. All the statements within the starting and ending brackets are executed with each execution of the for loop.
The following example shows how the for statement can be used to set up a loop that iterates five times. When the script begins to execute, the value of i is 0. Each time the loop executes, the value of i is incremented by 1 (in the i++ clause). Although this example displays just five lines of text that show the value of i as it grows, I think you can see that it can be easily modified to do just about anything, such as repeatedly prompting the user for input and iteratively processing that input.
<HTML>
<HEAD>
<TITLE>Script 2.12 – Demonstration of a for loop</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript” TYPE=”Text/JavaScript”>
<!– Start hiding JavaScript statements
for (i=0; i<5; i++) {
document.write(“Watch as the variable grows with each
iteration: “,i,”<BR>”);
}
// End hiding JavaScript statements –>
</SCRIPT>
</BODY>
</HTML>
Figure 2.9 shows the result of loading the previous example. If you run this script yourself, you should take note just how quickly the scripts executes.
An example of using a for loop to perform iterative processes