The JavaScript Diaries: Part 5
Loops
Loops are used to repeat a process or section of code a specified number of
times. There are three types of loop statements: for, while,
and do while. These statements use the increment/decrement
and comparison
operators we learned about previously.
The for Statement
A for statement is useful because it allows for the declaration of the variable, the condition for the statement, and the incremental expression all in one. The format of a for statement is:
for (initialExpression; condition; incrementExpression) {
statements
}
|
Here is a sample for statement. Be sure to try this yourself.
for (var newNum=1; newNum < 4; newNum++) {
document.write("This pass is #" + newNum + "<br>");
}
|
The ++ increment operator is used to increase the value of the variable by one. You can also use the decrement operator, --:
for (var newNum=9; newNum>4; newNum--) {
document.write("This pass is #" + newNum + "
");
}
If you needed to increase/decrease the value of the variable by a different number, say 3, you would write it as: newNum+=3 or newNum-=3, respectively.






Loading Comments...