3 Example(s) of JavaScript break statement


Description :

JavaScript break statement is used to jump out of loop. See the code snippet:


JavaScript break statement Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<p>A loop with a break statement.</p>
<p id="sample"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
    if (i == 2) { break; }
    text += i + "<br>";
}
document.getElementById("sample").innerHTML = text;
</script>
</body>
</html>

Output

Description :

Example of JavaScript break statement:


JavaScript break statement Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<p id="sample"></p>
 <script>
    var x = 1;
    document.write("Entering the loop<br /> ");
     while (x < 10)
         {
            if (x == 4){
               break; 
            }
            x = x + 1;
            document.write( x + "<br />");
         }
         
         document.write("Exiting the loop!<br /> ");
         
      </script>
</body>
</html>

Output

Description :

Example of JavaScript break statement:


JavaScript break statement Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
 <script>
document.write("Entering the loop!<br /> ");
outerloop: 
         
for (var i = 0; i < 5; i++)
{
    document.write("Outerloop: " + i + "<br />");
    innerloop:
    for (var j = 0; j < 5; j++)
    {
    if (j > 3 ) break ; 
    if (i == 2) break innerloop; 
    if (i == 4) break outerloop; 
    document.write("Innerloop: " + j + " <br />");
    }
    }
      document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>

Output