Loop Control: break, continue
Loop Control: break and continue
When executing loops, standard sequential execution isn't always enough. You may want to exit a loop early when a searched item is found, or skip the current iteration when encountering invalid data. JavaScript provides break and continue for granular loop control.
1. The break Statement: Emergency Exit
The break statement immediately terminates the entire loop and jumps execution to the first statement following the loop:
Real-World Example: Linear Search
Without break, the loop would uselessly continue checking the remaining elements, wasting CPU cycles!
2. The continue Statement: Skip to Next Iteration
The continue statement does not terminate the loop. Instead, it skips the rest of the current iteration and jumps immediately to the next iteration (evaluating the increment and condition):
Real-World Example: Filtering Bad Data
3. Summary: break vs continue
| Statement | What it does | Loop Status |
|---|---|---|
break | Terminates loop immediately | Exits the loop entirely |
continue | Skips remainder of current step | Continues with next step |
4. Labeled Statements (Advanced)
When working with nested loops, a standard break only exits the innermost loop. To break out of an outer loop from within an inner loop, use a label:
Practice Quiz
break statement inside a loop?continue statement inside a loop?break is executed inside an inner loop of a nested loop structure without labels, what happens?break be used inside a switch statement?String Basics
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| While and Do-While Loops | String Basics |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.