break

Terminates execution of the loop it's running in.

 

This example has the val variable initialised to a starting value of 4 and checks in the for loop if the value has reached 7, if not carry on, otherwise break out of the loop:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
	<script type="text/javascript">
		var val ;

		for (val = 4; val < 15; val++) {
			document.write("val = " + val + "<br>");

			if (val == 7){
				break;
			}
		}
	</script>
	</body>
</html>

Save & refresh browser:

val = 4
val = 5
val = 6
val = 7

Leave a Reply