Over and Over with the for Loop

with the for Loop

Computers are great at performing tasks over and over again  with the for Loop(that’s part of their charm—they can do the grunt work). One of the ways JavaScript lets you perform tasks over and over is with the for loop, which you can use to execute code multiple times (such as displaying  “Happy Birthday!” 25 times for a 25-year-old). Here’s what the for loop looks like formally speaking (as before, the parts in square brackets are optional, and you replace the parts in italics with your own JavaScript):

for ([initial-expression]; [condition]; [increment-expression]) {
statements
}

You usually use a for loop with a loop index, also named a loop counter. A loop index is a variable that keeps track of the number of times the loop has been executed. In the initialexpression part, you usually set the loop index to a starting value; in the condition part, you test that value to see if you still want to keep on looping; and the increment-expression lets you increment the loop counter with the for Loop.

Here’s an example with the for Loop, for.html. This example adds the numbers from 1 to 100—something you’d probably be pleased to let a computer do rather than add up all the numbers yourself. In this case, you want the computer to loop 100 times, which you can do with a for loop and a loop index variable like this:

var loopIndex;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
-
-
-
}

Here with the for Loop

the variable loopIndex starts at 1, and at the end of each time through the loop, 1 is added to loopIndex with the expression loopIndex++, because the JavaScript ++ operator increments the variable you apply it to by one (the — operator decrements the variable you apply it to by 1). And the loop above stops when the value in loopIndex is greater than 100 (that is, the loop keeps looping while loopIndex <= 100). So to add the numbers from 1 to 100, you just have to add this code:

var loopIndex;
var total = 0;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
total += loopIndex;
}

Here’s what it looks like in a web page with the for Loop, for.html:

<html>
<head>
<title>Using the for loop</title>
<script language="javascript">
function display()
{
var loopIndex;
var total = 0;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
total += loopIndex;
}
document.getElementById('targetDiv').innerHTML =
"The total of 1 to 100 is " + total;
}
</script>
</head>
<body>
<h1>Using the for loop</h1>
<input type="button" onclick="display()" value="Click Here">
<div id="targetDiv">
</div>
</body>
</html>

andcombd