HTML and CSS Reference
In-Depth Information
Labels. Labels allow you to name control statements ( while , do/while , for , for/in , and
switch ) so that you can refer to them by that name elsewhere in your program. They
can be named the same as any other legal identifier that is not a reserved word. By
themselves, labels do nothing. Labels are optional, but are often used to control the
flow of a loop. A label looks like this, for example:
topOfLoop:
Normally, if you use loop-control statements such as break and continue , the control
is directed to the innermost loop. There are times when it might be necessary to switch
control to some outer loop. This is where labels most often come into play. By prefixing
a loop with a label, you can control the flow of the program with break and continue
statements as shown in Example 6.10. Labeling a loop is like giving the loop its own
name.
EXAMPLE 6.10
<script type="text/javascript">
1
outerLoop: for ( var row = 0; row < 10; row++){
2
for ( var col=0; col <= row; col++){
document.write("row "+ row +"|column " + col, "<br />");
3
if(col==3){
document.write("Breaking out of outer loop at column
4
" + col +"<br />");
5
break outerLoop ;
}
}
6
document.write("************<br />");
7
} // end outer loop block
</script>
EXPLANATION
1
The label outerLoop labels the for loop that follows it. It's like giving the for loop
its own name so that it can be referenced by that name later.
2
This is a nested for loop. As the program executes the row and column numbers
are displayed.
3
If the expression is true, the break statement, with the label, causes control to go
to line 8; it breaks out of the outer: loop. A break statement without a label would
cause the program to exit just the loop to which it belongs.
4
The value of row and col are displayed as the inner loop iterates.
5
The break statement with the label causes control to go to line 8.
6
Each time the inner loop exits, this row of stars will be printed (see Figure 6.9).
Notice that the row of stars is not printed when the loop is exited on line 5.
7
The closing curly brace closes the outer for loop block on line 1.
 
Search WWH ::




Custom Search