2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-07-20 11:46:15 +02:00
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.
2020-06-30 12:47:33 +02:00
2023-06-28 14:57:06 +01:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2020-06-30 12:47:33 +02:00
----
2023-07-20 11:46:15 +02:00
myLabel: if (i % 2 == 0) { // Noncompliant: Labeling an if statement
2020-06-30 12:47:33 +02:00
if (i == 12) {
console.log("12");
break myLabel;
}
2021-10-19 11:43:21 +02:00
console.log("Even number, but not 12");
2020-06-30 12:47:33 +02:00
}
----
2023-06-28 14:57:06 +01:00
Instead of using a label with these nested `if` statements, this code block should be refactored.
[source,javascript,diff-id=1,diff-type=compliant]
----
2023-07-20 11:46:15 +02:00
if (i % 2 == 0) { // Compliant
2023-06-28 14:57:06 +01:00
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.
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2020-06-30 12:47:33 +02:00
----
2023-07-20 11:46:15 +02:00
outerLoop: for (let i = 0; i < 10; i++) { // Compliant
2023-06-28 14:57:06 +01:00
for (let j = 0; j < 10; j++) {
if (condition(i, j)) {
break outerLoop;
}
}
2020-06-30 12:47:33 +02:00
}
----
2021-06-02 20:44:38 +02:00
2023-06-28 14:57:06 +01:00
2023-06-20 09:35:51 +01:00
== Resources
=== Documentation
2023-07-20 11:46:15 +02:00
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label[MDN - label]
2023-06-20 09:35:51 +01:00
2023-06-28 14:57:06 +01:00
=== Related rules
- S1119 - Labels should not be used
2023-06-20 09:35:51 +01:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]