Mastering JavaScript Labels: Simplifying Control Flow
Learn how to effectively utilize labeled statements in JavaScript to streamline control flow in your code. Explore the power of labels for efficient navigation within nested loops and conditionals.
Understanding JavaScript Labels
In JavaScript, a labeled statement is just a statement that has a name (label) attached to it. You can then use this label with break or continue statements to control the flow of your code, allowing you to jump to that specific labeled statement from within nested loops or conditionals.
You can use a label to identify a statement, and later refer to it using a break
or continue
statement. Note that JavaScript has no goto statement;
you can only use labels with break
or continue
.
Any break
or continue
that references label
must be contained within the statement that's labeled by label. Think about label as a variable that's only available in the scope of statement.
If a break label;
statement is encountered when executing statement, execution of statement terminates, and execution continues at the statement immediately following the labeled statement.
continue label;
can only be used if statement is one of the looping statements. If a continue label;
statement is encountered when executing statement, execution of statement continues at the next iteration of the loop. continue;
without a label
can only continue the innermost loop, while continue label;
allows continuing any given loop even when the statement is nested within other loops.
Syntax
label: // Any JavaScript identifier that is not a reserved word.
statement // A JavaScript statement. break can be used within any labeled statement, and continue can be used within labeled looping statements.
Example
let str = '';
loop1: for (let i = 0; i < 5; i++) {
if (i === 1) {
continue loop1;
}
str = str + i;
}
console.log(str); // Expected output: "0234"
In this example, we have a labeled loop called loop1
which iterates from 0
to 4
using the variable i
. Within the loop, there's a condition: if i
is equal to 1
, the continue
statement is executed with the label loop1
, meaning it skips the rest of the loop and continues with the next iteration of loop1
.
So, when i
is 1
, it skips concatenating i
to the str
variable. For all other values of i
, it concatenates i
to str
.
Finally, when the loop finishes, str
contains the concatenated values of i
from 0
to 4
, excluding 1
. Hence, the expected output is "0234"
.