totn JavaScript

JavaScript: Break Statement

This JavaScript tutorial explains how to use the break statement with syntax and examples.

Description

In JavaScript, the break statement is used when you want to exit a switch statement, a labeled statement, or exit from a loop early such as a while loop or for loop.

Syntax

The syntax for the break statement in JavaScript is:

break [label_name];

Parameters or Arguments

label_name
Optional. An identifier name (or label name) for a statement.

Note

  • You use the break statement to terminate a loop early such as the while loop or the for loop.
  • If there are nested loops, the break statement will terminate the innermost loop.
  • You can also use the break statement to terminate a switch statement or a labeled statement.

Example

Let's look at an example that shows how to use a break statement in JavaScript.

How to use the Break Statement with the Switch Statement

You can use the break statement with the switch statement. This is the most common use of the break statement.

For example:

// Set the TechOnTheNet technology to JavaScript
var totn_technology = 'JavaScript';

switch (totn_technology) {
   case 'SQL':
     console.log('TechOnTheNet SQL');
     break;

   case 'JavaScript':
     console.log('TechOnTheNet JavaScript');
     break;

   default:
     console.log('Other TechOnTheNet technologies');
}

In this switch statement example, the break statement is used to terminate the switch statement so that once a match is found no further values are not evaluated.

This example will output the following to the web browser console log:

TechOnTheNet JavaScript

How to use the Break Statement with the While Loop

You can also use the break statement to terminate a loop early in JavaScript. Let's look at an example of how to terminate a while loop early using the break statement.

For example:

var counter = 1;

while (counter <= 5) {

   if (counter == 3) {
      break;
   }

   console.log(counter + ' - Inside while loop on TechOnTheNet.com');
   counter++;
}

console.log(counter + ' - Done while loop on TechOnTheNet.com');

In this while loop example, the break statement is used to exit the while loop early when the counter is equal to 3. Once the counter is 3, the while loop will terminate even though the while loop's condition is set to (counter <= 5).

This example will output the following to the web browser console log:

1 - Inside while loop on TechOnTheNet.com
2 - Inside while loop on TechOnTheNet.com
3 - Done while loop on TechOnTheNet.com