Mastering JavaScript Label Statements for Enhanced Loop Control
Written on
Chapter 1: Understanding JavaScript Label Statements
In a previous article discussing the break and continue statements, I may have left out an essential feature. These statements can only operate within loops, specifically targeting the innermost loop in nested structures. This limitation raises the question: can we manipulate the outer loops? Is there a way to exit the parent loop or bypass its iterations instead of just the inner one?
JavaScript includes a less commonly known feature that allows us to label loops, enabling the break and continue statements to target any loop within nested structures. The label statement serves as an identifier that can be referenced throughout the code.
To apply labels to JavaScript statements, simply prefix the statement with a label name followed by a colon. The syntax is as follows:
label:
statements
Here, "label" serves as an identifier, and "statements" can include any valid JavaScript code. For instance, you can label a loop and then use break or continue to control its execution.
Example:
markedLoop:
while (theMark === true) {
doSomething();}
Both break and continue can then be directed at the specified loop by referencing its label. The syntax for these commands is as follows:
break labelName;
continue labelName;
The continue statement, when used without a label, will only skip the current iteration of the innermost enclosing loop. It does not terminate the loop completely, unlike the break statement.
In a while loop, continue will jump back to the loop's condition. In a for loop, it moves to the final expression.
The break statement, when not using a label, will terminate the innermost enclosing loop or switch statement and pass control to the next line of code. However, with a label, break can exit any labeled block of code.
Example:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
break list;
text += cars[2] + "<br>";
text += cars[3] + "<br>";
}
document.getElementById("demo").innerHTML = text; // Output: BMW, Volvo
In the example above, the label "list" is attached to a series of string concatenations. The break statement targeting this label causes the output to only display two of the four car names.
Another illustration:
let x = 0;
let z = 0;
labelCancelLoops:
while (true) {
console.log('Outer loop: ' + x);
x += 1;
z = 1;
while (true) {
console.log('Inner loop: ' + z);
z += 1;
if (z === 5 && x === 3) {
break labelCancelLoops;} else if (z === 5) {
break;}
}
}
Output:
Outer loop: 0
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
Outer loop: 1
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
Outer loop: 2
Inner loop: 1
Inner loop: 2
Inner loop: 3
This example shows that when x is 3 and z is 5, the loop breaks out of the outer while loop. If the condition is not met, it will exit the inner loop instead.
Similarly, the continue statement works with labeled statements.
Example:
let i = 0;
let j = 10;
checkIandJ:
while (i < 4) {
console.log(i);
i += 1;
checkj:
while (j > 4) {
console.log(j);
j -= 1;
if ((j % 2) === 0) {
continue checkj;}
console.log(j + ' is odd.');
}
console.log('i = ' + i);
console.log('j = ' + j);
}
Output:
0
10
9 is odd.
9
8
7 is odd.
7
6
5 is odd.
5
i = 1
j = 4
1
i = 2
j = 4
2
i = 3
j = 4
3
i = 4
j = 4
In this scenario, the labeled statement checkIandJ contains another labeled statement checkj. When continue is invoked, the current iteration of checkj is terminated, and the loop reiterates until its condition is false. Once checkj completes, checkIandJ will continue until its own condition fails.
Multiple labels can be employed as shown in the last example, making them particularly useful for managing nested loops. They allow for conditional exits from loops, enhancing the control you have over your code.
That's all for now on label statements. I hope this article proves beneficial to you. If you think this information could help others, please share it. Your feedback and comments are always appreciated!
Thanks for reading!
This first video demonstrates how to effectively use JavaScript statement labels, providing a visual guide to their implementation and functionality.
The second video offers a comprehensive tutorial on using labels with break and continue in JavaScript programming, helping to solidify your understanding.