↑
Main Page
Iterative statements
if (i > 25)
alert(“Greater than 25.”); //one-line statement
else {
alert(“Less than or equal to 25.”); //block statement
}
You can also chain
if
statements together like so:
if (
condition1
)
statement1
else if (
condition2
)
statement2
else
statement3
Example:
if (i > 25) {
alert(“Greater than 25.”)
} else if (i < 0) {
alert(“Less than 0.”);
} else {
alert(“Between 0 and 25, inclusive.”);
}
Iterative statements
Iterative statements, also called loop statements, specify certain commands to be executed repeatedly
until some condition is met. The loops are often used to iterate the values of an array (hence the name)
or to work though repetitious mathematical tasks. ECMAScript provides four types of iterative state-
ments to aid in the process.
do-while
The
do-while
statement is a post-test loop, meaning that the evaluation of the escape condition is only
done after the code inside the loop has been executed. This means that the body of the loop is always
executed at least once before the expression is evaluated. Syntax:
do {
statement
} while (
expression
);
For example:
var i = 0;
do {
i += 2;
} while (i < 10);
It’s considered best coding practice to always use block statements, even if only one
line of code is to be executed. Doing so can avoid confusion about what should be
executed for each condition.
54
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 54
Free JavaScript Editor
Ajax Editor
©
→