Break & Continue
EasyIn plain terms
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next. Both work in for, while, and switch.
What you need to know
- •break: exit loop
- •continue: next iteration
- •Labels for nested loops
Try it yourself
Copy the code below and run it in your browser console or a code editor:
// Break - exit loop
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // 0,1,2,3,4
}
// Continue - skip iteration
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // 0,1,3,4
}
// Labeled break (nested loops)
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
}
}Learn more
Dive deeper with these trusted resources: