What is the purpose of the `break` and `continue` statements?
Topics
JavaScript
TL;DR
The break statement is used to exit a loop or switch statement prematurely, while the continue statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a for loop, break will stop the loop entirely, and continue will skip to the next iteration.
Purpose of the break and continue statements
break statement
The break statement is used to exit a loop or a switch statement before it has completed all its iterations or cases. This is useful when you want to stop the execution of the loop or switch based on a certain condition.
Example in a loop
Example in a switch statement
continue statement
The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. This is useful when you want to skip certain iterations based on a condition without exiting the loop entirely.
Example in a loop
Differences between break and continue
- The
breakstatement exits the loop or switch statement entirely. - The
continuestatement skips the current iteration and moves to the next iteration of the loop.
Further reading
Exercises
Check your understanding
Beta