In JavaScript loops and switch statements, the break and continue keywords give you fine control over how and when the loop runs.
break immediately stops the current loop or switch and exits it.continue skips the current iteration and moves on to the next one.for, while, and do...while loops.break when you have found what you need and can stop looping early.continue to skip certain values (e.g., even numbers, invalid input).Break syntax:
break Statement Syntax
break;
break labelName;
Continue syntax:
continue Statement Syntax
continue;
continue labelName;
When used without a label, break and continue only affect the innermost loop. With a label, they can target an outer loop.
for Loop
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop when i is 5
}
console.log(i);
}
// Output: 0 1 2 3 4
for Loop
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output: 1 3 5 7 9
while Loop
let count = 0;
while (true) {
console.log("Count is:", count);
count++;
if (count === 3) {
break; // Exit infinite loop when count reaches 3
}
}
// Output:
// Count is: 0
// Count is: 1
// Count is: 2
for (let i = 1; i <= 10; i++) {
if (i === 7) {
continue; // Skip number 7
}
console.log(i);
}
// Output: 1 2 3 4 5 6 8 9 10
break
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (j === 2) {
break; // Breaks inner loop when j is 2
}
console.log(`i=${i}, j=${j}`);
}
}
// Output:
// i=1, j=1
// i=2, j=1
// i=3, j=1
break
outerLoop:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerLoop; // Breaks the outer loop
}
console.log(`i=${i}, j=${j}`);
}
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
for loop, the loop stops completely when i reaches 5, so only 0 to 4 are printed.continue example, all even numbers are skipped, so only odd numbers appear in the output.while (true) loop would be infinite, but break stops it safely once count becomes 3.break only affects the inner loop, so the outer loop continues with the next value of i.break outerLoop stops the outer loop entirely as soon as i === 2 and j === 2.break when a safe exit condition occurs.break exits the entire current loop or switch immediately.continue skips the current iteration but keeps the loop running.break and continue; if logic feels complex, consider refactoring.1 to 10 but breaks the loop if the number is greater than 6.3 using continue.continue with a label and observe how control jumps to the next outer iteration.