JavaScript: break statement


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


break [label1]


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


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


<!DOCTYPE html>
<html lang="en">
<meta charset=utf-8>
<title>JavaScript break statement : Example-1
<link rel="stylesheet" type="text/css" href="example.css">
<script src="break-statement-example1.js">
<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" />
<p id="result">Your result will be displayed here.</p>

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.";
var z = 0;
var y;
for(y=1; y<=x; y++)
z = z + y;
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

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

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