The break statement terminates the current loop or other operator. The program continues running with the following statement. This could be useful when it is necessary to interrupt the cycle. Syntax looks as follows:
break[label];
An identifier associated with the label of the break statement is required if the statement is not a loop or switch. In general, this operator is not required.
Break and loop
Imagine, we have a group of people invited to an event. Let us have some information about each guest, including their age. To demonstrate the break
we will take into account the age of guests, that is we will form an array of ages. Depending on the person's age, we will be able to offer or refuse alcohol.
var agesOfGuests = [20, 25, 22, 15, 19];
for(var i = 0; i < agesOfGuests.length; i++)
{
if(agesOfGuests[i] >= 18)
{
alert(`Alcohol menu is available for guest number ${i+1}`);
}
else if (agesOfGuests[i] < 18)
{
alert(`Alcohol menu is blocked for guest ${i+1}`);
break;
}
}
/*
Alcohol menu is available for guest number 1
Alcohol menu is available for guest number 2
Alcohol menu is available for guest number 3
Alcohol menu is blocked for guest 4
*/
In the for
loop we are indexing each age value from the input agesOfGuests
array. If a value is greater than 18, the message (‘the alcohol menu is available') will be displayed using interpolation. Otherwise we will see an alternate message (‘alcohol is not available') and the break
operator will work.
By the way, in the interpolation we display the person index this way - i+1
- only for convenience and the usual kind of numbering. This is optional, another way could be done by defining such a cycle:
for(var i = 1; i <= agesOfGuests.length; i++)
Although there are 5 values in the array, we will see 4 messages only. The first three for people over 18 and one for people under 18. When the program enters a condition less than 18, it will meet the break
operatorand will leave the loop. That is why we will no longer get any results for people who are placed in the array after a person under 18 years old.
This happened because the break
operator, as we know, immediately leaves the loop. Therefore, the arrayGuestsAges[4]
value remained unprocessed.
Breaking the loop operator continues to execute code after the loop, if any is present. By the way, in this example instead of for
we could use loop while
or do…while
. Break
in this case would behave similarly.
Break and switch
Switch
statement is the most common form of break statements. In the following example, the break statement is used to stop the switch statement.
The idea of the switch
expression is to predict all possible outcomes depending on certain conditions. In the following example, depending on the person sex (male/female), we will see the corresponding message. If we meet the corresponding condition, only the condition for this value is fulfilled, aAnd other cases are not checked.
In general the optional break
exits each switch block. It can be specified in each case, in each block, but it is not mandatory. If you do not specify it, the following instruction from the switch block will be executed.
switch(value)
{
case "male":
alert("Turn right to WC.");
break;
case "female":
alert("Turn left to WC.");
break;
default:
alert("I do not understand you:(");
}
In this example the use of a break
is necessary. Otherwise the user would receive two messages ("Turn right" and "Turn left"), as a result could be confused where he should go.
Break with label
We know the break statement syntax allows use of a label reference
to break out of any code block. In loop
and switch
statements break
can be used without a label. But in other situations labels are required. By the way a break statement must always be nested within any label it references.
var array = ["Kate", "John", "Anna", "Alex"];
var names = "";
list:
{
names += array[0] + ", ";
names += array[1] + ", ";
break list;
names += array[2] + ", ";
names += array[3] + ", ";
}
/*
Kate, John
*/
Break and errors
A break statement, with label or without it, cannot be used within the body of a function that is nested within the current loop or switch that the break statement is intended to break out of.
The next example will generate a SyntaxError because a break
statement must always be nested within any label it references. This condition is not met here.
blockFirst:
{
console.log('The first');
break blockSecond; // SyntaxError
}
blockSecond:
{
console.log('The second');
}
Well we already know a break
statement must always be nested within any label it references. In case this condition is not met we get an error.
Break with for…of statement
You should also be confident in using the break statement when operating with for loops that have the of statement. Let’s review the most basic instance:
const list = ['z', 'x', 'y']
for (const item of list) {
if (item === 'x') break
console.log(item)
} // Expected output: z
We have a list with three strings. Within this for…of
loop, we indicate when to terminate the loop using the break statement. As in the example with numbers, the item you show initializes the break, not allowing the prompt to be equal or greater. Accordingly, because we specified a break with an item === ‘x’
, the expected output for this command equals z
.
Continue vs break
In JavaScript are two statements that can jump out of a code block. We have already learned one of them - break
. The other one - continue
statement.
If the break
interrupts the loop completely, the continue
skips only one iteration in this loop. Moreover, the interruption of the iteration occurs when a certain condition is met. Later continue
passes to the next iteration and keep on work.
By the way, the continue
as well as the break
can be used with the label statement
. But the continue
statement can only be used in loops.
Okay, let's recall in memory an example with an array of ages of guests who are invited to the party. Let's try to apply continue
in this example:
var agesOfGuests = [20, 25, 22, 15, 19];
for(var i = 0; i < agesOfGuests.length; i++)
{
if(agesOfGuests[i] >= 18)
{
alert(`Alcohol menu is available for guest number ${i+1}`);
}
else if (agesOfGuests[i] < 18)
{
alert(`Alcohol menu is blocked for guest ${i+1}`);
continue;
}
}
/*
Alcohol menu is available for guest number 1
Alcohol menu is available for guest number 2
Alcohol menu is available for guest number 3
Alcohol menu is blocked for guest 4
Alcohol menu is available for guest number 5
*/
From the output it is clear that this time all the guests of the party were evaluated, including those who are on the list later than a minor.
Therefore specifically in this case to use the continue
is more justified. But, it cannot be said that this is always the case. Sometimes it is necessary to use a break
.
Although they are slightly similar in syntax, parameters, and possibly in terms of use, they are not interchangeable. These expressions are separate.
Alternatives to the break statement
As with dozens of other use cases in JavaScript, there are a few alternatives to stopping a for
loop. However, you should be aware that their functionality is limited, meaning that the break statement is always a preferred option.
Also, other options are not always working with the for loop scenarios, eventually making them more nuanced. Still, let’s review them to understand the primary differences:
break
statement andfor
loop:
let data = [
{name: 'Bob'},{name: 'Michael'},{name: 'James'}
]
for (let obj of data) {
console.log(obj.name)
if (obj.name === 'Michael') break;
} // Expected output: Bob Michael
every
keyword for arrays:
let data = [
{name: 'Bob'},{name: 'Michael'},{name: 'James'}
]
data.every(obj => {
console.log(obj.name)
return !(obj.name === 'Michael')
}) // Expected output: Bob Michael
some
prototype for arrays:
let data = [
{name: 'Bob'},{name: 'Michael'},{name: 'James'}
]
data.some(obj => {
console.log(obj.name)
return (obj.name === 'Michael')
}) // Expected output: Bob Michael
As you can see, in all three examples, the output is the same. However, when you’re using the for…of
loop and the break
statement, you can make the most of its functionality.
Not only is this approach the slickest and most readable, it also does allow performing await operations within it. When using every and some approaches and arrays, you don’t have a way to benefit from the loop repeatability.
Exercise tasks
Task 1. Use the
break
statement for a simple list with three strings, such as “zebra,” “giraffe,” and “gazelle.” Using thefor
loop, terminate the command to show only the first two strings.
Solution:
const animals = ["zebra", "giraffe", "gazelle"]
for (const animal of animals) {
if (animal === "gazelle") break
console.log(animal)
} // Expected output: zebra giraffe
Task 2. Use the
break
statement to work with the numbers labeled asi
. Leti == 50
, and limit it to 55. Then, introduce an if statement and terminate the loop from running with a cap limit of 51. Finally, log the results through a console:
Solution:
for (let i = 50; i <= 55; i++) {
if (i == 51) {
break;
}
console.log(i);
} // Expected output: 50
Task 3. Create nested loops and use the
break
statement to terminate theinner
loop. The data set for this task is as follows:
i = 5, i <= 6
j = 7, j <= 8
Inner loop: i == 5:
for (let i = 5; i <= 6; i++) {
for (let j = 7; j <= 8; j++) {
if (i == 5) {
break;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Expected output:
// i = 6, j = 7
// i = 6, j = 8