JavaScript
    About Lesson

    The break statement in JavaScript is used to terminate a loop, switch, or in conjunction with a labeled statement.

     

    Syntax

    break;

     

    Break in Loops

    In loops, the break statement ends the loop entirely and moves the execution to the line of code immediately following the loop.

    Here’s an example:

    for (let i = 0; i < 10; i++) {
      if (i === 5) {
        break;
      }
      console.log(i);
    }

    In this example, the loop will terminate when i equals 5, so the numbers 0 through 4 will be logged to the console.

     

    Break in Switch Statement

    In a switch statement, break is used to prevent the “fallthrough” behavior of switch statements, where all cases are evaluated until a break is encountered or the switch statement ends.

    Here’s an example:

    let fruit = 'Apple';
    
    switch (fruit) {
      case 'Apple':
        console.log('Apple is ₹ 32');
        break;
      case 'Banana':
        console.log('Banana is ₹ 48');
        break;
      default:
        console.log('Invalid fruit');
        break;
    }

     

    In this example, once a match is found and its code is executed, the break statement prevents the rest of the cases from being checked.

     

    Break with Labeled Statement

    A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. The break statement, when used with a label, allows you to break out to any other place in your code.

    Here’s an example:

    let x = 0;
    let z = 0;
    labelCancelLoops: while (true) {
      console.log('Outer loops: ' + x);
      x += 1;
      z = 1;
      while (true) {
        console.log('Inner loops: ' + z);
        z += 1;
        if (z === 10 && x === 10) {
          break labelCancelLoops;
        } else if (z === 10) {
          break;
        }
      }
    }

     

    In this example, break labelCancelLoops; statement breaks the outer loop labeled labelCancelLoops.

     

    The break statement in JavaScript provides you with a lot of control over the flow of your code. It allows you to optimize your code and make it more readable and efficient.