Skip to content

JavaScript break if using in Loop | Example code

  • by

JavaScript break if used in a loop to break the loop iterations. If the condition is true then break the current loop. It can also use to stop 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading