Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Break in JavaScript

Js Break in JavaScript

? JavaScript break Statement


What is break?

  • The break statement 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 4
  • Works with for, while, and do...while loops.


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

  • break only 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?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql