Javascript Loops
for Loops
A for loop constitutes a
statement which consists of three
expressions, enclosed in
parentheses and separated by
semicolons, followed by a block of
statements executed in the loop.
This definition may, at first,
sound confusing. Indeed, it is
hard to understand for loops
without seeing them in action.
A for loop resembles the
following:
for (initial-expression;
condition; increment-expression) {
statements
}
The initial-expression is a
statement or variable declaration.
(See the section on variables for
more information.) It is typically
used to initialize a counter
variable. This expression may
optionally declare new variables
with the var keyword.
The condition is evaluated on each
pass through the loop. If this
condition evaluates to true, the
statements in statements are
performed. When the condition
evaluates to false, the execution
of the for loop stops. This
conditional test is optional. If
omitted, the condition always
evaluates to true.
The increment-expression is
generally used to update or
increment the counter variable.
The statements constitute a block
of statements that are executed as
long as condition evaluates to
true. This can be a single
statement or multiple statements.
Although not required, it is good
practice to indent these
statements from the beginning of
the for statement to make your
code more readable.
Check out the following for
statement. It starts by declaring
the variable i and initializing it
to zero. It checks whether i is
less than nine, performs the two
successive statements, and
increments i by one after each
pass through the loop:
var n = 0;
for (var i = 0; i < 3; i++) {
n += i;
alert("The value of n is now " +
n);
}
Try it yourself: Click
this link
while Loops
The while loop, although most
people would not recognize it as
such, is for's twin. The two can
fill in for one another - using
either one is only a matter of
convenience or preference
according to context. while
creates a loop that evaluates an
expression, and if it is true,
executes a block of statements.
The loop then repeats, as long as
the specified condition is true.
The syntax of while differs
slightly from that of for:
while (condition) {
statements
}
condition is evaluated before
each pass through the loop. If
this condition evaluates to true,
the statements in the succeeding
block are performed. When
condition evaluates to false,
execution continues with the
statement following statements.
statements is a block of
statements that are executed as
long as the condition evaluates to
true. Although not required, it is
good practice to indent these
statements from the beginning of
the statement.
The following while loop
iterates as long as n is less than
three.
var n = 0;
var x = 0;
while(n < 3) {
n++;
x += n;
alert("The value of n is " + n + ". The
value of x is " + x);
}
Try it for yourself: Click
this link
|