Next page | Contents page |

Loop statements

while loops


while (boolean expr)
  statement

or


do
  statement
while (boolean expr);

Example:


var j = 0;

while (j < 10)
{
  alert (j + " " + j * j);
  j++;
}

for loops


for ( init ; test ; incr )
  statement

init and incr usually involve assignments. Both can be comma-separated lists of statements.

init sets initial conditions.

test is a boolean condition: the loop executes as long as it is true.

incr is executed after statement, every time round the loop.

init and incr are optional but there must always be the two semicolons to mark the sections of the loop header.

Example:


for (var i = 0, j = 10; i < j; i++, j--)
{
  if (3 * i > 2 * j)
    alert (i + " " + j);
}

Efficiency

When writing loops it is important to identify repetitive computations that can be done before the loop rather than every time round it. This is possibly the most important factor to look out for, to make your code run faster.

Another kind of loop

There is another kind of loop in JavaScript but we can only introduce it after we have covered Objects.

Next page | Contents page |