How to Use JavaScript’s break Statement

The break statement lets you stop loop execution in HTML programming, even if the stop expression conditions aren’t met. There are many reasons to use the break statement. For example, you might want to stop loop execution when the application experiences an error. The following example shows how to use a break statement to stop application execution. In this case, processing stops when the application finds data of the incorrect type.

function OptionalArgument(param)
{
  // Determine whether there were any params passed.
  if (arguments.length == 0)
  {
   // Display an error message and exit.
   document.getElementById("Result").innerHTML =
     "Nothing Passed!";
   return;
  }
  
  // Create a string to hold the arguments.
  var Result = new String();
 
  // Process each of the arguments in turn.
  for (var i = 0; i < arguments.length; i++)
  {
   // Verify that the argument is of the right type.
   if (typeof(arguments[i]) != 'string')
   {
     // When the argument is incorrect, stop
     // loop execution.
     break;
   }
  
   // Add to the argument string.
   Result += arguments[i] + "<br />";
  }
 
  // Display the results onscreen.
  document.getElementById("Result").innerHTML = Result;
}

In this case, the example stops processing the input arguments immediately after finding an input argument of a type other than string. Consequently, when the application calls OptionalArgument('Red', 'Green', 'Blue'), the application displays all three arguments.

However, when the application calls OptionalArgument('Red', 'Green', true, 'Orange'), it displays only Red and Green. Even though Orange is also a correct argument, it appears after true, which is an incorrect argument. Execution stops with true. If the application were to call OptionalArgument(true, 'Red', 'Yellow', 'Orange'), the output would be blank because the first argument is incorrect.

The break statement is used as an exceptional condition. You stop execution because the loop can’t continue for some reason. As a consequence, the break statement normally appears as part of an if structure. The if statement defines the exceptional condition. Any loop cleanup you want to perform, such as finalizing a variable’s state, must appear before the break statement.

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

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.