while loops

while loops are very similar to for loops. However, they do not contain a counter. A while loop evaluates an expression, stated in parenthesis after the keyword while.

while (expression)
{
  ... code of loop goes here ...
}

If this expression returns true, the statement block of the while loop is executed. At the end of the loop, the initial expression is evaluated again. If it still returns true, the loop is executed again. The loop continues to be executed as long as the initial condition remains true or if a break statement within the block is invoked.

Example:

 

Code:

function doWhileLoop(formField)
{
  var count = 0;
  while (confirm("Loop again?"))
  {
    formField.value = ++count;
  }
  alert("You looped " + count + " times.");
}

while loops w. continue/break

Just as for loops, the behavior of while loops can be manipulated with the reserved words continue and break.

Example:

Limit: 5 loops

 

Code:

function doWhileContinue(formField)
{
  var count = 0;
  while (confirm("Loop again?"))
  {
    if (count == 4)
    {
      break;
    }
    formField.value = ++count;
  }
  
  if  (count == 4)
  {
    alert("You reached the looping limit.");
  }
  else
  {
    alert("You looped " + count + " times.");
  }
}