break & continue
Overview
The break statement completely "jumps out" of a loop, terminating it instantly.
The continue statement "jumps over" one iteration in the loop. It stops the current execution block and goes straight back to the condition check for the next iteration.
Syntax
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips printing 3, moves directly to i = 4
}
console.log(i); // Outputs: 1, 2, 4, 5
}for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Kills the entire loop entirely!
}
console.log(i); // Outputs: 1, 2
}Common Pitfalls
Trying to use
breakorcontinueinside modern array iteration methods like.map(),.forEach(), or.filter(). These keywords are reserved ONLY for traditional loops (for,while,for...of). Using them in.map()will throw a SyntaxError.
Interview Questions
Can you use the break keyword inside a .forEach() array loop?
No, you cannot break out of a .forEach() loop. If you need the ability to short-circuit or break early to save performance, you must use a traditional for loop or a for...of loop.
Real-World Example
Searching a massive list of 10,000 users for a specific ID. Once found, you use break to stop the loop instantly, saving CPU cycles instead of checking the remaining 9,999 users.
let match = null;
for (let i = 0; i < users.length; i++) {
if (users[i].id === targetId) {
match = users[i];
break; // Stop searching!
}
}Check Your Knowledge
Test your understanding of break & continue with these quick questions.