70 lines
1.9 KiB
Plaintext

== Why is this an issue?
Loop counters, such as variables used to track the iteration count in loops, should not be assigned from within the loop body to avoid unexpected behavior and bugs. It can inadvertently lead to an infinite loop or make the loop behavior more complex and harder to reason about.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
const names = [ "Jack", "Jim", "", "John" ];
for (let i = 0; i < names.length; i++) {
if (!names[i]) {
i = names.length; // Noncompliant: The loop counter i is assigned within the loop body
} else {
console.log(names[i]);
}
}
----
To avoid these issues, you should update the loop counter only in the loop's update statement, typically located at the end of the loop body or within the loop header.
[source,javascript,diff-id=1,diff-type=compliant]
----
const names = [ "Jack", "Jim", "", "John" ];
for (let i = 0; i < names.length; i++) {
if (!names[i]) {
break;
} else {
console.log(names[i]);
}
}
----
Alternatively, you should use the `for...of` statement if your intention is only to iterate over the values of an iterable object.
[source,javascript]
----
const names = [ "Jack", "Jim", "", "John" ];
for (const name of names) {
if (!name) {
break;
} else {
console.log(name);
}
}
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for[for]
* MDN web docs - link:++https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of++[``++for...of++``]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols[Iteration protocols]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this assignment of "x".
=== Highlighting
* Primary: assigned counter variable
* Secondary: counter variable in ``++for++``-loop signature
endif::env-github,rspecator-view[]