The break Statement
break immediately exits the current loop, skipping any remaining iterations.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // loop stops at 5
}
console.log(i);
}
// 0 1 2 3 4
Try it Yourself →
Break is commonly used to stop searching once a desired element is found.
const fruits = ["apple", "banana", "cherry", "date"];
let found = false;
for (const fruit of fruits) {
if (fruit === "cherry") {
found = true;
break;
}
console.log("Checking " + fruit);
}
console.log("Found: " + found);
The continue Statement
continue skips the current iteration and moves to the next one.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
console.log(i);
}
// 1 3 5 7 9
Use continue to filter out unwanted values without nesting the entire loop body inside an if.
Labeled Statements
Labels let you break or continue an outer loop from inside a nested loop.
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // breaks both loops
}
console.log("i=" + i + " j=" + j);
}
}
// i=0 j=0 i=0 j=1 i=0 j=2 i=1 j=0