Labels allow specifying a target statement to jump to using the break
or continue
statements. It’s possible to assign a
label to any statement or block of statements. However, using it with any statement can create a complex control flow path, making the code harder to
understand and maintain.
myLabel: if (i % 2 == 0) { // Noncompliant: Labeling an if statement
if (i == 12) {
console.log("12");
break myLabel;
}
console.log("Even number, but not 12");
}
Instead of using a label with these nested if
statements, this code block should be refactored.
if (i % 2 == 0) { // Compliant
if (i == 12) {
console.log("12");
} else {
console.log("Even number, but not 12");
}
}
The rule considers that while
, do-while
, for
, and switch
statements don’t create complex
control flow paths, thus these statements are not reported.
outerLoop: for (let i = 0; i < 10; i++) { // Compliant
for (let j = 0; j < 10; j++) {
if (condition(i, j)) {
break outerLoop;
}
}
}