JavaScript Break
Break statement is used to break the immediate loop or switch statement, and carry on with the execution of next statements in the script.
The syntax of break statement is
break;
JavaScript break statement can be used inside the following statements.
- switch
- for
- for in
- for of
- while
- do while
Usually, break statement is used conditionally inside a loop statement.
We will go through examples with break statement for each of these statements.
Break Switch Statement
In the following example, we use break statement at the end of each case block in switch statement.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var value=2;
var displayOutput='';
switch(value){
case 1:
displayOutput += "Value is 1.";
break;
case 2:
displayOutput += "Value is 2.";
displayOutput += " This is second statement.";
break;
case 3:
displayOutput += "Value is 3.";
break;
default :
displayOutput += "Value is default."
}
document.getElementById('output').innerHTML += displayOutput;
</script>
</body>
</html>
Break For Loop
In the following example, we use break statement to exit For loop when i
becomes 4.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
for (let i = 0; i < 10; i++) {
if (i == 4) {
break;
}
document.getElementById('output').innerHTML += i + ' - hello world\n';
}
</script>
</body>
</html>
Break For-in Loop
In the following example, we use break statement to exit For-in loop when the value corresponding to any key is 22
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = {name: 'Apple', age: '22', location: 'California'};
for (key in obj) {
let value = obj[key];
if (value == 22) {
break;
}
document.getElementById('output').innerHTML += value;
}
</script>
</body>
</html>
Break For-of Loop
In the following example, we use break statement to exit For-of loop when the value of item is orange
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = ['apple', 'banana', 'orange'];
for (item of obj) {
if (item == 'orange') {
break;
}
document.getElementById('output').innerHTML += item + '\n';
}
</script>
</body>
</html>
Break While Loop
In the following example, we use break statement to exit While loop when i == 5
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
while (i < 10) {
if (i == 5) {
break;
}
document.getElementById('output').innerHTML += i + '\n';
i++;
}
</script>
</body>
</html>
Break Do-While Loop
In the following example, we use break statement to exit Do-While loop when i == 5
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
do {
if (i == 5) {
break;
}
document.getElementById('output').innerHTML += i + '\n';
i++;
} while (i < 10);
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned what break statement is in JavaScript, its syntax, and usage with examples.