This JavaScript tutorial explains how to use the ruin statement with syntax and examples.
Description
In JavaScript, the damage announcement is used when you choose to exit a switch statement, a labeled statement, or exit from a loop early such as a while loop or for loop.
Syntax
The syntax for the smash assertion in JavaScript is:
break [label_name];
Parameters or Arguments
label_name Optional. An identifier title (or label name) for a statement.
Note
You use the ruin assertion to terminate a loop early such as the whilst loop or the for loop. If there are nested loops, the destroy declaration will terminate the innermost loop. You can additionally use the destroy announcement to terminate a change assertion or a labeled statement.
Example
Let’s look at an example that suggests how to use a spoil statement in JavaScript.
How to use the Break Statement with the Switch Statement
You can use the destroy statement with the swap statement. This is the most common use of the damage statement.
For example:
// Set the TechOnTheNet technology to JavaScript
var totn_technology = 'JavaScript';
switch (totn_technology) {
case 'SQL':
console.log('TechOnTheNet SQL');
break;
case 'JavaScript':
console.log('TechOnTheNet JavaScript');
break;
default:
console.log('Other TechOnTheNet technologies');
}
In this swap statement example, the wreck assertion is used to terminate the swap announcement so that as soon as a in shape is found no in addition values are now not evaluated.
This instance will output the following to the net browser console log:
TechOnTheNet JavaScript
How to use the Break Statement with the While Loop
You can additionally use the spoil statement to terminate a loop early in JavaScript. Let’s look at an instance of how to terminate a while loop early the use of the break statement.
For example:
var counter = 1;
while (counter <= 5) {
if (counter == 3) {
break;
}
console.log(counter + ' - Inside while loop on TechOnTheNet.com');
counter++;
}
console.log(counter + ' - Done while loop on TechOnTheNet.com');
In this while loop example, the spoil assertion is used to exit the whilst loop early when the counter is equal to three Once the counter is 3, the whilst loop will terminate even although the whilst loop’s situation is set to (counter <= 5).
This instance will output the following to the web browser console log:
1 - Inside while loop on TechOnTheNet.com
2 - Inside while loop on TechOnTheNet.com
3 - Done while loop on TechOnTheNet.com
Leave a Review