Menu Close

JavaScript Break and Continue

In this guide, you will learn about JavaScript Break and JavaScript Continue statements along with examples. In the previous tutorial, we have seen all about JavaScript variables and JavaScript Boolean along with examples.

The Break Statement

JavaScript Break statement is used to jump out of a loop.

Example:

<!doctype html> 
<html> 
  <head>
  </head> 
  <body> 
<button onclick="myFunction()">Click Here</button>
<p id="num"></p>
  </body> 
  
<script>
function myFunction()
{
var i = 0;
var text = "";
while (i < 10 )
{
	if ( i == 5 )
		{
			break;			
		}
	
	text += i + "<br>";
	i++;
} 
document.getElementById('num').innerHTML = text;
};

</script>
</html>

When you will execute the above code and click on the Click Here button 0 to 4 numbers will be shown, 5 will be not showing because define a condition when the value of i will be 5, Then break statement terminates the loop.

The Continue Statement

JavaScript Continue statement is used to stop the current iteration of the program and continue with next iteration.

<html> 
  <head>
  </head> 
  <body> 
<button onclick="myFunction()">Click Here</button>
<p id="num"></p>
  </body> 
  
  
<script>
function myFunction()
{
var i = 0;
var text = "";
for (i = 0; i < 10; i++)
{
	if ( i == 5 )
		{
			continue;			
		}
	text += i + "<br>";	
} 
document.getElementById('num').innerHTML = text;
};
</script>
</html>

When you will execute above code and click on Click Here button 0 to 9 number will be show except 5, 5 will be not showing because define a condition, when value of i will be 5, Then continue statement stop the current iteration and continue with next means 6.

Conclusion

In this tutorial, we have seen all about JavaScript break and JavaScript continue statement along with the examples.

The JavaScript break statement is basically used, when you want to stop the execution of the loop on a specific condition and the JavaScript continue statement is used when you want to stop the execution of the loop on the specific condition and continue with the next.

If you like this JavaScript break and continue statement article, please share and keep visiting for further JavaScript tutorials.

JavaScript Variables
JavaScript Function

Related Posts