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="disabled"
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 to insert an item into an array at a specific index (JavaScript)?
What you want is the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
Ref: https://bit.ly/2BXbp04
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework