The break and continue keywords in JavaScript allow us to disrupt/disturb the flow of the running loop.
We don’t always want the loop to run up until the test condition fails. Sometimes, when the iteration is too large, we want to get out of the loop before all the iterations happen or we want to skip some iterations.
This is where JavaScript introduces break and continue.
JavaScript break keyword 💔
The break keyword in JavaScript allows us to “break out” of the loop or exit the loop before all the possible iterations happen.
The break keyword is mostly used when there is a certain condition we might meet and when we meet that condition we don’t want the loop to run anymore, so we exit the loop.
In this example, we have used the for loop which is explained in our 👉 JavaScript For Loop lesson.
Example 1
console.log("Can you count the number of days in a week?");
console.log("Sure");
for (let i = 1; i <= 365; i++) {
console.log(i);
// Here, we don't want to run the loop until the 365th time.
// When we reach number "7", we exit the loop using the "break" keyword.
if (i === 7) {
break;
}
}
Output
Can you count the number of days in a week?
Sure
1
2
3
4
5
6
7
Example 2
const friends = ["Monica", "Chandler", "Joey", "Ross", "Phoebe", "Rachel"];
for (let i = 0; i < friends.length; i++) {
console.log(friends[i]);
if (friends[i] === "Joey") {
break;
}
}
console.log("How you doin?");
Output
Monica
Chandler
Joey
How you doin?
JavaScript continue keyword ▶
The continue keyword in JavaScript allows us to “skip” some iterations in a loop when a certain condition is satisfied, and “continue” the next iteration.
Example 1
console.log("Can you show me only the even numbers upto 10?");
console.log("Sure");
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
// Here, the ampersand "%" operator returns the remainder when divided by 2.
// As for odd numbers, the remainder is not 0, so we skip the iteration when we encounter odd numbers.
// Hence, the "console.log" below will not run for odd numbers.
continue;
}
console.log(i);
}
Output
Can you show me only the even numbers upto 10?
Sure
2
4
6
8
10
Example 2
const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
console.log("On which days are you available?");
console.log("Let me see...");
for (let i = 0; i < daysOfWeek.length; i++) {
if (daysOfWeek[i] === "Sun" || daysOfWeek[i] === "Sat") {
continue;
}
console.log(daysOfWeek[i]);
}
Output
On which days are you available?
Let me see...
Mon
Tue
Wed
Thu
Fri
In this way, we can control the flow of a loop using the break and continue keyword.