How to Use the Break Statement in JavaScript

Normally JavaScript loops run as long as some condition is satisfied. The break statement allows the programmer to break out a loop immediately and unconditionally. It is also used to terminate processing of a case in a switch statement.

Things You'll Need

  • JavaScript editor
Show More

Instructions

  1. Use the Break Statement in JavaScript

    • 1

      Find or code the for or while loop from which you want to break out.

    • 2

      Code the break statement at the point where you want to break out from the loop. Example:
      while (true) {
      ...
      if (number_errors > 100) break;
      ...
      }

    • 3

      Code a break statement following the statements after a case statement inside a switch statement. Otherwise, execution will continue with the statements for the following case, which is probably not what you want. Example:
      switch (name) {
      case "Bob": alert ("You're Bob."); break;
      ...
      }

Tips & Warnings

  • Coding a break outside a loop or switch will result in an error.

Related Searches:

Comments

You May Also Like

Related Ads

Featured