JavaScript break Statement
The JavaScript break statement is used to terminate a loop or switch statement early. It allows you to control the flow of execution by stopping the current loop or case block when a certain condition is met.
Common use cases for the break statement include:
- Early exit from loops: Stop looping when a specific condition is met.
- Switch-case control: Exit a switch block after executing a matching case.
- Nested loops: Break out of inner loops when needed.
What You'll Learn
In this guide, you'll learn how to use the break statement in JavaScript loops and switch statements, and how it can help manage control flow more effectively.
Understanding the break Statement
The break statement works by immediately exiting the current loop or switch block, skipping any remaining code within it. It's commonly used inside for or while loops.
// Example: break in a for loop
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i); // Outputs 1 and 2
}
// Example: break in a for loop
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i); // Outputs 1 and 2
}
In the example above, the loop prints numbers 1 and 2. When the number is 3, the break statement is executed, and the loop exits immediately.
Output:
1
2
1
2
Example 1: Breaking a while loop
You can also use break with a while loop. Here's an example:
let i = 0;
while (i < 10) {
if (i === 5) {
break;
}
console.log(i);
i++;
}
let i = 0;
while (i < 10) {
if (i === 5) {
break;
}
console.log(i);
i++;
}
How It Works:
- while (i < 10): This starts a loop that will run as long as i is less than 10.
- if (i === 5): The loop will exit when i equals 5.
- break: Exits the loop immediately when the condition is met.
- So the loop prints 0 to 4 and exits when i reaches 5.
Output
0
1
2
3
4
0
1
2
3
4
Example 2: Breaking a for loop when searching for an item
You can use the break statement in a for loop to stop the loop early when a specific item is found. Here's an example:
// Search loop example: Break when item is found
const items = ['apple', 'banana', 'cherry', 'date'];
const searchItem = 'cherry';
for (let item of items) {
if (item === searchItem) {
console.log("Found cherry!");
break; // Exit loop once the item is found
}
// Search loop example: Break when item is found
const items = ['apple', 'banana', 'cherry', 'date'];
const searchItem = 'cherry';
for (let item of items) {
if (item === searchItem) {
console.log("Found cherry!");
break; // Exit loop once the item is found
}
How It Works:
- for (let item of items): This starts a loop that goes through each element in the items array.
- if (item === searchItem): The loop checks if the current item matches searchItem.
- break: Exits the loop immediately when the item is found.
- So the loop prints a message and stops when it finds 'cherry'.
Output
Found cherry!
Found cherry!
Example 3: Breaking out of nested loops
When working with nested loops, a break statement will only exit the innermost loop. Here's an example:
// Nested loop example
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (j === 2) {
break;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Nested loop example
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (j === 2) {
break;
}
console.log(`i = ${i}, j = ${j}`);
}
}
How It Works:
- for (let i = 1; i <= 3; i++): Outer loop that runs from 1 to 3.
- for (let j = 1; j <= 3; j++): Inner loop that also runs from 1 to 3.
- if (j === 2): The inner loop stops when j equals 2.
- break: Exits the inner loop only; the outer loop continues.
- So for each i, only j = 1 is printed.
Output
i = 1, j = 1
i = 2, j = 1
i = 3, j = 1
i = 1, j = 1
i = 2, j = 1
i = 3, j = 1
Example 4: Breaking out of multiple loops using a label
JavaScript supports labeled break statements, which let you exit outer loops from within inner ones. This is useful when you need to stop all looping once a certain condition is met.
// Labeled break to exit both loops
outerLoop: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerLoop; // Exit both loops
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Labeled break to exit both loops
outerLoop: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerLoop; // Exit both loops
}
console.log(`i = ${i}, j = ${j}`);
}
}
How It Works:
- outerLoop:: A label for the outer loop that we can reference.
- break outerLoop;: This breaks out of both the inner and outer loops when the condition is met.
- In this example, the loops stop completely when i = 2 and j = 2.
- Only the iterations before that condition are printed.
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Exercises
Try the following exercises to practice using break:
1. Write a loop that prints numbers from 1 to 10, but stops at 6.
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
2. Write a program that keeps prompting the user for input until they enter "exit".
// Note: This works in browser environments
while (true) {
let input = prompt("Type something (type 'exit' to quit):");
if (input === "exit") {
break;
}
console.log("You typed:", input);
}
// Note: This works in browser environments
while (true) {
let input = prompt("Type something (type 'exit' to quit):");
if (input === "exit") {
break;
}
console.log("You typed:", input);
}
*Tip: Try changing the conditions or loop types to deepen your understanding of break in JavaScript.
Frequently Asked Questions
What is the break statement in JavaScript?
What is the break statement in JavaScript?
The break statement is used to exit a loop or a switch case early, stopping further iterations or execution of code.
When should I use the break statement in a loop?
When should I use the break statement in a loop?
You should use the break statement when you want to stop a loop prematurely based on a condition, such as finding a specific element or meeting a certain condition.
Can I use break inside a switch statement?
Can I use break inside a switch statement?
Yes, the break statement is commonly used in a switch statement to exit a particular case once the code block for that case is executed.
What happens if I forget to use break in a switch statement?
What happens if I forget to use break in a switch statement?
If you forget to use the break statement in a switch case, the code will 'fall through' and execute the next case statement as well.
Can the break statement be used in a nested loop?
Can the break statement be used in a nested loop?
Yes, the break statement can be used in a nested loop. It will exit the innermost loop it is placed in, but if you want to break out of all loops, you can use labeled statements.
What's Next?
Now that you know how to exit loops early with break, next explore the continue statement, which lets you skip to the next iteration instead of exiting the loop.