How to Use break in JavaScript: Syntax and Examples
In JavaScript, the
break statement is used to immediately exit a loop or a switch case. When break runs, the program stops the current loop or switch and continues with the code after it.Syntax
The break statement can be used inside loops (for, while, do-while) or switch statements to stop execution early.
- break; - exits the nearest enclosing loop or switch.
javascript
break;Example
This example shows how break stops a for loop when a condition is met, exiting the loop early.
javascript
for (let i = 1; i <= 5; i++) { if (i === 3) { break; } console.log(i); }
Output
1
2
Common Pitfalls
One common mistake is expecting break to exit multiple nested loops or functions, but it only exits the closest loop or switch. Also, using break outside loops or switches causes errors.
javascript
/* Wrong: break outside loop causes error */ // break; // SyntaxError /* Right: break inside loop */ for (let i = 0; i < 3; i++) { if (i === 1) { break; } console.log(i); }
Output
0
Quick Reference
| Use Case | Effect |
|---|---|
| Inside loops | Stops the loop immediately and continues after it |
| Inside switch | Exits the current case to avoid running next cases |
| Outside loops/switch | Causes a syntax error |
Key Takeaways
Use
break to exit the nearest loop or switch immediately.break only stops one loop or switch, not multiple nested ones.Never use
break outside loops or switch statements.It helps control flow by stopping loops early when a condition is met.