The break statement: Exiting loops early
What you'll learn: How to use break to immediately exit a loop before it naturally completes.
Sometimes you don't need to finish all iterations of a loop—you've found what you're looking for or met a specific condition. The break statement lets you escape the current loop instantly and jump to the code right after it.
How break Works
When JavaScript encounters break inside a loop, it:
- Immediately stops executing the loop body
- Exits the nearest enclosing loop (while, do-while, for, for...of, or for...in)
- Continues execution with the first statement after the loop
Think of it like finding your keys in a messy drawer—once you spot them, you stop searching through the rest.
Basic Example
// Find the first negative number
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop immediately when i equals 5
}
console.log(i); // Logs: 0, 1, 2, 3, 4 (then stops)
}
console.log("Loop finished");
The loop terminates at i === 5, never reaching 6, 7, 8, or 9.
Practical Use Case
let numbers = [2, 4, 6, 7, 8, 10];
let foundOdd = false;
for (let num of numbers) {
if (num % 2 !== 0) {
foundOdd = true;
break; // Found an odd number, no need to continue
}
}
console.log(foundOdd); // true
Without break, you'd wastefully check every remaining element even after finding what you need.
Key Takeaway: The break statement immediately terminates the nearest enclosing loop and resumes execution at the next statement after the loop—use it to exit early when continuing would be unnecessary or wasteful.