Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to label a block in JavaScript?
A block statement groups zero or more statements. In languages other than JavaScript, it is known as a compound statement. Labels in JavaScript provide a way to identify blocks of code, which is particularly useful for controlling nested loops with break and continue statements.
Syntax
Here's the basic syntax for a block statement:
{
// List of statements
}
To add a label to a block, use the following syntax:
labelName: {
// Statement list
}
Labeling Loops
Labels are most commonly used with loops to control flow in nested structures:
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
// break outerLoop; - exits both loops
// break innerLoop; - exits only inner loop
}
}
Example with Break Statement
The following example demonstrates how labels control the flow with break statements in nested loops:
<html>
<body>
<script>
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop!
Example with Continue Statement
Labels also work with continue to skip iterations in nested loops:
<html>
<body>
<script>
outer: for (let i = 0; i < 3; i++) {
document.write("Outer loop: " + i + "<br>");
inner: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
document.write("Skipping outer iteration<br>");
continue outer; // Skip to next outer loop iteration
}
document.write("Inner loop: " + j + "<br>");
}
}
</script>
</body>
</html>
Outer loop: 0 Inner loop: 0 Inner loop: 1 Inner loop: 2 Outer loop: 1 Inner loop: 0 Skipping outer iteration Outer loop: 2 Inner loop: 0 Inner loop: 1 Inner loop: 2
Key Points
- Labels must be followed by a colon (:)
- Label names follow the same rules as variable names
- Labels are most useful for controlling nested loops
- Use
break labelNameto exit a specific labeled block - Use
continue labelNameto skip to the next iteration of a labeled loop
Conclusion
Labels provide precise control over nested loops in JavaScript. While not commonly used, they're essential for complex loop structures where you need to break or continue outer loops from inner loops.
