The break and continue statements allow you to "jump" in and out
of loops. They are essential for optimizing performance and handling specific data cases
during iteration.
The break statement "jumps out" of a loop completely. It
stops the loop from running further, even if the loop condition is still true.
for (let i = 0; i < 10; i++) {
if (i === 3) { break; } // Loop stops completely when i is 3
console.log(i); // Result: 0, 1, 2
}
The continue statement "jumps over" one iteration in the
loop. If a specified condition occurs, it skips that iteration and continues with the
next iteration in the loop.
for (let i = 0; i < 5; i++) {
if (i === 3) { continue; } // Skips the rest of the code when i is 3
console.log(i); // Result: 0, 1, 2, 4
}
To break or continue inside nested loops, you can use labels. A label is
a name followed by a colon (e.g., loopHome:).
list: {
console.log("item 1");
console.log("item 2");
break list; // Exits the labeled block immediately
console.log("item 3"); // This won't run
}
break: Exits the loop entirelycontinue: Skips the current iteration and goes to the
next onefor, while, and do...while loops
break is also mandatory in switch blocks