JavaScript Break and Continue statements



The break statement is used to break out of the loop.

continue is used to skip an iteration in a loop.


Break Statement

We have already seen the break statement in previous chapters of this tutorial. It is used to break out of switch() statements.

The break statement can be used to break out of a loop.

After the break statement breaks out of the loop, the code after the loop will continue to be executed (if any):

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>点击按钮,测试带有 break 语句的循环。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
	var x="",i=0;
	for (i=0;i<10;i++){
		if (i==3){
    			break;
			}
    	x=x + "该数字为 " + i + "<br>";
    }
	document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

Since this if statement has only one line of code, the curly braces can be omitted:

for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}



##Continue statement

continue statement Interrupts the iteration in the loop if the specified condition occurs, and then continues with the next iteration in the loop. This example skips value 3:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>点击下面的按钮来执行循环,该循环会跳过 i=3 的步进。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
	var x="",i=0;
	for (i=0;i<10;i++){
  		if (i==3){
    		continue;
    	}
		x=x + "该数字为 " + i + "<br>";
  	}
	document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Run Instance»Click the "Run Instance" button to view Online Example


JavaScript Tags

As you saw in the chapter on switch statements, JavaScript statements can be tagged.

To label a JavaScript statement, add a colon before the statement:

label:
statements
The break and continue statements are just Statements that can jump out of code blocks.

Syntax:

break
labelname;
continue
labelname;
The continue statement (with or without label reference) can only be used within a loop.

break statement (without label reference), can only be used in a loop or switch.

Referenced through tags, the break statement can be used to break out of any block of JavaScript code:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<script>
cars=["BMW","Volvo","Saab","Ford"];
list:{
	document.write(cars[0] + "<br>"); 
	document.write(cars[1] + "<br>"); 
	document.write(cars[2] + "<br>"); 
	break list;
	document.write(cars[3] + "<br>"); 
	document.write(cars[4] + "<br>"); 
	document.write(cars[5] + "<br>"); 
}
</script>

</body>
</html>

Run Example»Click the "Run Instance" button to view the online instance