The break is one of the reserved keywords in JavaScript and we often associate it with when wanting to break the loop. This article is going to present some theoretical basics that are necessary to understand the break statement and some of the most common examples of break statement applications. For a beginning, let’s take a look at the official definition, and afterward we will take each part of it, explain how it works, and see for ourselves through examples.
With a break statement, you can exit or break the current loop, switch, or label statement. After the break statement, your program continues to execute the code if there is any code that follows the statement that was escaped.
The break statement and a loop
We already mentioned in the introduction that the break statement is often associated with loops, be it a for loop, for – in loops, while or a do – while loop. When you use the break statement in a loop, the break statement will break or escape the loop and will eventually continue to execute the code after the loop, of course, if there is any code.
The break statement in a while loop
The example below shows how a while loop works together with a break statement – we loop the code, but break the loop when our variable i is 5:
var understandBreak = "";
var i = 0;
while (i < 10) {
understandBreak += "
The number is " + i;
i++;
if (i === 5) {
break;
}
}
The following example below shows a function that contains a break statement. The break statement will again exit the while loop when i is 5, and will then return the value 5 * a.
function understandBreak(a) {
var i = 0;
while (i < 10) {
if (i === 5) {
break;
}
i += 1;
}
return i * a;
}
The break statement in a for if loop
In this example, the break statement will exits our for if loop when i is 5 and will continue to execute the code after the loop:
for (i = 0; i < 10; i++) {
if (i === 5) { break; }
console.log("The number is " + i);
}
The break statement and a switch statement
The break statement is also often used with switch statements and its purpose is the same as it is with loops - it exits a switch block and therefore ends completing the code inside that block.
Let's have a look at what is going on in the example below. We have a list of months and we're using the built-in JavaScript method getMonth to get a current month when we click on a button. So what the break statement does, in this case, is that it terminates a switch block to make sure that only one case is executed.
<p>Click this button to see what month it is today.</p>
<button onclick="currentMonth()">Click here</button>
<p id="month"></p>
<script>
function currentMonth() {
var month;
switch (new Date().getMonth()) {
case 0:
month = "January";
break;
case 1:
month = "February";
break;
case 2:
month = "March";
break;
case 3:
month = "April";
break;
case 4:
month = "May";
break;
case 5:
month = "June";
break;
case 6:
month = "July";
break;
case 7:
month = "August";
break;
case 8:
month = "September";
break;
case 9:
month = "October";
break;
case 10:
month = "November";
break;
case 11:
month = "December";
break;
}
document.getElementById("month").innerHTML = "Today is a month " + month;
}
Another example of a break statement in a switch statement could look like the one below. Again, in this example, a break statement ends a switch statement when a case is matched and the code has run, in our example, that would be the case "basketball".
const player = "basketball";
switch (player) {
case "basketball":
console.log("A basketball team has 5 players on the field.");
break;
case "volleyball":
console.log("A volleyball team has 6 players on the field.");
break;
case "soccer":
console.log("A soccer team has 11 players on the field.");
break;
}
Can we use the break statement with an optional label reference?
Yes, and this is very important - if we do not use the label reference, we can only use the break statement in a loop or a switch statement. But, if we use a label reference, we can exit any JavaScript code block. Obviously, a label reference is optional only when we use the break statement in a loop or a switch statement. When we are outside that loop or a switch statement scenario, we have to use the label reference if we want the break statement to work. This way we will be able to exit a labeled statement, but as already said, the break statement needs to be nested within the referenced label. Let's take a look at an example of using a break statement with a label reference below:
var fruits = ["banana", "strawberry", "apple", "pear", "kiwi"];
var content = "";
checklist: {
content += fruits[0] + "
";
content += fruits[1] + "
";
content += fruits[2] + "
";
break checklist;
content += fruits[3] + "
";
content += fruits[4] + "
";
}
// the output will be banana, strawberry, apple - the break statement has a label checklist.
Nesting a break statement within a label that statement references
At this point it is important to bring out a break statement must be nested within any label it references, let's take a look at an example below, where we have an blockInn nested inside blockOut.
blockOut: {
blockInn: {
console.log('1');
break blockOut; // breaks out of both blockOut and blockInn
console.log(':-('); // skipped
}
console.log('2'); // skipped
}
How to break in labeled blocks that throw
Below we have an example of a code that again uses break statements with labeled blocks. However, there is a problem because the break statement is inside blockFirst but references blockSecond. Therefore JavaScript gives us a SyntaxError. In general, with labeled blocks, we must always nest a break statement in a label it references.
blockFirst: {
console.log('1');
break blockSecond; // SyntaxError: label not found
}
blockSecond: {
console.log('2');
}
What about break statement within functions?
You cannot use a break statement inside a body of a function that is nested either inside a loop or switch statement that the break statement is intended to exit, whether the break statement is used with or without a label. If you do, you will most certainly encounter a syntax error. Below we'll show you an example, where we use a break statement inside a function that is nested in a loop:
function testBreakInside(a) {
var i = 0;
while (i < 10) {
if (i === 5) {
(function() {
break;
})();
}
i += 1;
}
return i * a;
}
testBreakInside(1); // SyntaxError: Illegal break statement
In this example, we'll show you an example where we use a break statement inside a labeled block, and the purpose of a break statement is to exit it:
blockOne: {
console.log('1');
( function() {
break blockOne; // SyntaxError: Undefined label 'blockOne'
})();
}
What else should I know about the break statement?
It is worth mentioning that the break statement can be closely connected to the continue statement, which breaks one loop iteration under specific circumstances and then continues with the next loop iteration. In the example below our program will skip the value of 5. let's take a look:
for (let i = 0; i < 15; i++) {
if (i === 5) { continue; }
text += "Our number is " + i + "
";
}
//the example above will give results such as "Our number is 1, Our number is 2 etc.... Then it will skip the statement with a value 5 and end with Our number is 14.