w3resource
JavaScript Statements

JavaScript: break statement

Description

The break statement is used to terminate a loop, switch or label statement.

Syntax

break [label1]

Parameter

lable1: Identifier associated with the label of the statement. The parameter is required if the statement is not a loop or switch.

Example:

The following web document demonstrates how break statement can be used.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript break statement : Example-1
</title>
<link rel="stylesheet" type="text/css" href="example.css">
<script src="break-statement-example1.js">
</script>
</head>
<body>
<h1>JavaScript : break statement</h1>
<form name="w3rfrom" onsubmit="w3rfunction();return false;">
<input type="text" placeholder="Input a number bwtween 2 to 10"
id="number" size="30" />
<input type="submit" value="Submit" />
</form>
<p id="result">Your result will be displayed here.</p>
</body>
</html>

JS Code

function w3rfunction(){
'use strict';
var x = document.getElementById("number").value;
if(x < 2 || x > 10){
document.getElementById("result").innerHTML = "The number is not within the range.";
}
else
{
var z = 0;
var y;
for(y=1; y<=x; y++)
{
z = z + y;
if(y===x)
{
break;
}
}
document.getElementById("result").innerHTML = 'The sum of numbers between  1 to '+ x +' is: '+ z;
}
}

View the example in the browser

Practice the example online

See the Pen break-1 by w3resource (@w3resource) on CodePen.




New Content: Composer: Dependency manager for PHP, R Programming