Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

The break Statement

The break statement provides you with a means of exiting a loop early. The break statement is commonly used to exit a loop when a value has reached or exceeded a set limit, or when searching through an array, when you've found the data for which you were searching.

The example below increments the variable x each time through the loop. Within the loop is an if statement that tests if x is greater than 8, and if so, executes a break statement.

var x = 0;
while (x < 12)
{
  x++;
  if(x > 8) break;
}
alert("loop exited when x = " + x);

The example below searches the day array for the day name "Wednesday", and, upon finding it, executes a break statement to end the loop.

var day = new Array("Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday","Sunday");
var index = 0;
while(index < day.length)
{
  if(day[index] == "Wednesday") break;
  index++;
}
alert("Found " + day[index]);

Remember if you code nested loops, a break statement in an inner loop will not cause program flow to also exit an outer loop.

var x = 0;
var y = 0;
while(y < 12)
{
  while (x < 3)
  {
    if(y > 3) break;
    x++;
  }
  y++;
}
alert("loop exited x = " + x + " y = " + y);

In the example above, the inner loop contains a break statement to cause it to exit when y is greater than 3, but it exits only the inner loop, the outer loop continues to increment y.

More Java Script Code:
• Java Script prompt Message Box
• Comparison Operators
• Java Script Math.sin Method
• Java Script Data Types
• Java Script Reserved Words
• Find a Character or a Substring Within a String
• The Navigator Object
• Remove Blank Spaces From Ends of a String
• JavaScript to Concatenate Strings
• The do/while Loop

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro


Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2019 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268