JavaScript break if using in Loop | Example code

  • by

JavaScript break if used in loop to break the loop iterations. If condition is true then break the current loop. It can also used to stops the execution of more code inside the switch.

JavaScript break if examples

Simple example code break out of for loop if i is equal to 3.

<!DOCTYPE html>
<html>
<head>

  <script>
    for (i = 0; i < 10; i++) {
      console.log(i)

      if (i === 3) { 
        console.log('Break')
        break; 
      }
    }
  </script>

</head>
</html>

Output:

JavaScript break if using in Loop

Break out of a switch block when a case is true:

let day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
}

Do comment if you have any doubts or suggestions on JS break code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.