w3resource

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.


Previous: JavaScript: label statement
Next: JavaScript: continue statement

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

How do I redirect to another webpage?

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace.

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ref: https://bit.ly/37JdWH8