JavaScript Break Statement
Learn how to exit loops and switch statements early
🔄 What is the Break Statement?
The
break
statement is used to exit or "break out" of loops and switch statements before they complete naturally. It's like an emergency exit!
// Simple break example
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit the loop when i equals 3
}
console.log(i);
}
// Output: 1, 2
Console Output:
2
Break Statement Uses
For Loops
Exit for loops early
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
While Loops
Stop while loops conditionally
let count = 0;
while (true) {
if (count === 3) break;
count++;
}
Switch Cases
Prevent case fall-through
switch (day) {
case 'Monday':
console.log('Start of week');
break;
case 'Friday':
console.log('TGIF!');
break;
}
Search Operations
Stop when item is found
let found = false;
for (let item of array) {
if (item === target) {
found = true;
break;
}
}
🔹 Break in For Loops
Use break to exit for loops when a condition is met:
// Finding the first even number
let numbers = [1, 3, 7, 8, 9, 12];
let firstEven;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
firstEven = numbers[i];
console.log("Found first even number:", firstEven);
break; // Stop searching once found
}
}
Console Output:
🔹 Break in While Loops
Break can prevent infinite loops or exit based on conditions:
// User input simulation
let userInput = "";
let attempts = 0;
while (true) {
attempts++;
// Simulate getting user input
userInput = attempts === 3 ? "quit" : "continue";
console.log(`Attempt ${attempts}: ${userInput}`);
if (userInput === "quit") {
console.log("User chose to quit!");
break; // Exit the infinite loop
}
if (attempts >= 5) {
console.log("Too many attempts!");
break; // Safety exit
}
}
Console Output:
Attempt 2: continue
Attempt 3: quit
User chose to quit!
🔹 Break in Switch Statements
Break prevents "fall-through" in switch cases:
let grade = 'B';
switch (grade) {
case 'A':
console.log("Excellent!");
break; // Without this, it would continue to case 'B'
case 'B':
console.log("Good job!");
break; // Stops here for grade 'B'
case 'C':
console.log("You can do better!");
break;
default:
console.log("Invalid grade");
break; // Good practice even in default
}
Console Output:
🔹 Nested Loops and Break
Break only exits the innermost loop:
// Break only affects the inner loop
for (let i = 1; i <= 3; i++) {
console.log(`Outer loop: ${i}`);
for (let j = 1; j <= 3; j++) {
if (j === 2) {
console.log(" Breaking inner loop");
break; // Only exits the inner loop
}
console.log(` Inner loop: ${j}`);
}
}
Console Output:
Inner loop: 1
Breaking inner loop
Outer loop: 2
Inner loop: 1
Breaking inner loop
Outer loop: 3
Inner loop: 1
Breaking inner loop