In JavaScript, the break and continue statements are used to control the flow of loops (for, while, and do...while). They provide mechanisms to exit or skip iterations based on specific conditions.
The break statement terminates the current loop immediately and exits the loop entirely. After the break statement is executed, the control flow moves to the statement following the loop.
When you want to stop the loop once a specific condition is met.
break;for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit the loop when i equals 3
}
console.log(i);
}
// Output: 1, 2In this example:
- The loop terminates completely when
iis3.
The continue statement skips the rest of the current iteration and moves to the next iteration of the loop. It does not terminate the loop, only the current iteration.
When you want to skip specific iterations of a loop based on a condition.
continue;for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i equals 3
}
console.log(i);
}
// Output: 1, 2, 4, 5In this example:
- The loop skips the
console.logstatement wheniequals3and continues with the next iteration.
| Feature | break |
continue |
|---|---|---|
| Effect on Loop | Terminates the loop entirely. | Skips the current iteration. |
| Control Flow | Moves to the statement after the loop. | Moves to the next iteration. |
| Usage | To exit the loop under certain conditions. | To skip specific iterations. |
for (let i = 1; i <= 10; i++) {
if (i === 3) {
continue; // Skip the iteration for i = 3
}
if (i === 7) {
break; // Exit the loop completely when i = 7
}
console.log(i);
}
// Output: 1, 2, 4, 5, 6const numbers = [1, 2, 3, 4, 5];
const target = 3;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === target) {
console.log(`Found ${target} at index ${i}`);
break; // Stop searching once the target is found
}
}const numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
if (num % 2 === 0) {
continue; // Skip even numbers
}
console.log(num);
}
// Output: 1, 3, 5- The
breakstatement is used to terminate a loop when a specific condition is met. - The
continuestatement is used to skip certain iterations without stopping the entire loop. - Both statements provide flexibility in controlling the flow of loops, making them essential tools for writing efficient and concise code in JavaScript.