10.1 The break Statement
The break
and continue
statements are used for controlling loop flow in JavaScript.
They let you immediately exit a loop or skip to the next iteration, respectively.
The break Statement
The break
statement is used to immediately exit a loop. When break
is encountered inside
a loop, the loop is terminated, and control is passed to the next block of code outside the loop.
Syntax:
break;
Exiting a for loop:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exits the loop when i = 5
}
console.log(i);
}
// Output: 0 1 2 3 4
10.2 The continue Statement
The continue
statement is used to skip the current iteration of a loop and proceed to the next iteration. Unlike
the break
statement, continue
does not terminate the entire loop, it only skips the current iteration.
Syntax:
continue;
Skipping an iteration in a for loop:
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skips the current iteration if i is even
}
console.log(i);
}
// Output: 1 3 5 7 9
Skipping an iteration in a while loop:
let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) {
continue; // Skips the current iteration if i is even
}
console.log(i);
}
// Output: 1 3 5 7 9
10.3 Comparing break and continue Statements
Statement | Description | Usage Examples |
---|---|---|
break | Immediately terminates the execution of the current loop | Exiting a loop when a condition is met |
continue | Skips the current iteration of the loop and proceeds to the next iteration | Skipping a loop iteration when a condition is met |
The break
and continue
statements are powerful tools for controlling loop flow in
JavaScript. break
is used to immediately finish a loop, while continue
skips the current
iteration and moves to the next one. Using these statements correctly allows you to create more flexible
and efficient code that's easier to understand and maintain.
10.4 Using break and continue in Nested Loops
Nested loops are loops inside other loops. The break
and continue
statements can be
used in such constructions to control the flow of both the outer and inner loops.
Example with break in nested loops:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break; // exits the inner loop
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Output:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
// i = 2, j = 0
// i = 2, j = 1
// i = 2, j = 2
Example with continue in nested loops:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
continue; // skips the iteration of the inner loop
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Output:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
// i = 1, j = 2
// i = 2, j = 0
// i = 2, j = 1
// i = 2, j = 2
GO TO FULL VERSION