Js Break in JavaScript
? JavaScript break Statement
What is break?
The
breakstatement exits (breaks out of) a loop or a switch statement immediately.Useful to stop iteration or skip remaining cases.
Usage with Loops
for (let i = 0; i < 10; i++) { if (i === 5) { break; // exit loop when i is 5 } console.log(i);}// Output: 0 1 2 3 4Works with
for,while, anddo...whileloops.
Usage with Switch Statements
const fruit = "apple";switch(fruit) { case "banana": console.log("Banana"); break; case "apple": console.log("Apple"); break; // Without break, execution falls through to next case case "orange": console.log("Orange"); break; default: console.log("Unknown fruit");}Without
break, cases fall through, executing subsequent cases unintentionally.
Important Notes
breakonly exits the innermost loop or switch.To break outer loops inside nested loops, use labeled statements:
outerLoop: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) { break outerLoop; // breaks outer loop } console.log(i, j); }}Need examples on labeled breaks or how to control loops with continue and break together?