How to Create while Loops in JavaScript

Web developers commonly use while loops when there’s no definite ending for a loop in HTML programming. The environment or data must meet a specific condition before the loop stops. With this in mind, it’s easier to create an infinite loop with a while loop than it is with a for loop because you’re not always sure about the condition ending the loop. It’s important to plan while loops carefully.

How to use the basic while loop in JavaScript

A basic while loop tests for the ending condition immediately. If the ending condition is met, then the loop never executes. This type of loop is useful when you may or may not need to perform processing on some type of variable data.

For example, a while loop of this sort works perfectly with a function that accepts zero or more optional arguments. The fact that there may not be any arguments to process means that the while loop will never execute. The following example shows such a scenario.

function OptionalArgument(param)
{
 // Display the default output.
 document.getElementById("Result").innerHTML =
   "Nothing Passed!";
  
  // Create a string to hold the arguments.
  var Result = new String();
 
  // Process each of the arguments in turn.
  while (param.length > 0)
  {
   // Remove the current argument.
   var Argument = param.shift();
  
   // Verify that the argument is of the right type.
   if (typeof(Argument) == 'string')
   {
     // Add to the argument string.
     Result += Argument + "<br />";
   }
  }
 
  // Display the results onscreen.
  document.getElementById("Result").innerHTML = Result;
}

In this example, OptionalArgument() receives an array as input. When someone sends something other than an array, the function acts as if the user didn’t send anything at all. The array can contain any number of elements — the function doesn’t care how many or how few.

The while loop checks the length of param. When param contains even a single element, the loop begins processing the data. The call to shift() removes the first element from the array, making the array shorter by one element. When this Argument is of type string, it’s added to Result.

The interesting features of this example are that it’s shorter than the for loop example and that this version will execute slightly faster because there are fewer comparisons performed during each loop. Whether it’s actually easier to understand depends on how you write applications. Some developers would probably find this form easier to understand as well, but you should use the forms that work best for you as a developer.

How to use the do...while loop in JavaScript

A do...while loop works precisely the same as a standard while loop except that the ending expression is evaluated at the end of the loop. This means that a do...while loop always executes at least once.

Developers commonly use do...while loops for menus, reading files, and other processes that may require some setup within the loop before the loop can evaluate the expression. The following example shows how you could use a do...while loop to create a continuous processing scenario.

function AddItems()
{
  // Create an input variable.
  var Input = new String();
 
  // Keep accepting input until the user
  // types quit.
  do
  {
   // Obtain new input.
   Input = prompt("Type a new value (quit to exit):");
  
   // Verify the user hasn't typed quit.
   if (Input.toUpperCase() != 'QUIT')
   {
     // Add the input to the array.
     DataStore.push(Input);
    
     // Display the result onscreen.
     DisplayArray(DataStore, "Result")
   }
  } while (Input.toUpperCase() != 'QUIT')
}

The example relies on a global Array named DataStore to hold the entries. Obviously, there’s no input to process when the application begins, so the user makes a request to add an item. At this point, Input has no data, and there’s nothing to define whether there’s anything to do.

The do...while loop works perfectly because you don’t want Input to contain anything until the user puts it there. The user keeps adding items. When the application sees the word quit in any form, the data entry stops.

Notice how the application checks for the ending condition in this case. You should always convert input to uppercase or lowercase and then check it against a standardized capitalization. Otherwise, you can’t be sure whether the user will type quit, QUIT, Quit, or even qUit. This approach ensures you capture the keyword whatever form the user types it in.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com