50 lines
2.0 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
A `for` loop is a type of loop construct that allows a block of code to be executed repeatedly for a fixed number of times. The `for` loop is typically used when the number of iterations is known in advance, and consists of three parts:
2020-06-30 12:47:33 +02:00
* The initialization statement is executed once at the beginning of the loop, and is used to initialize the loop counter or any other variables that may be used in the loop.
* The loop condition is evaluated at the beginning of each iteration, and if it is `true`, the code inside the loop is executed.
* The update statement is executed at the end of each iteration, and is used to update the loop counter or any other variables that may be used in the loop.
2020-06-30 12:47:33 +02:00
[source,javascript]
----
for (initialization; condition; update) { /*...*/ }
----
All three statements are optional. However, when the initialization and update statements are not used, it can be unclear to the reader what the loop counter is and how it is being updated. This can make the code harder to understand and maintain.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
for (;condition;) { /*...*/ } // Noncompliant: Only the condition is specified
----
When only the condition expression is defined in a ``++for++`` loop, a ``++while++`` loop should be used instead to increase readability. A ``++while++`` loop consists of a single loop condition and allows a block of code to be executed repeatedly as long as the specified condition is true.
[source,javascript,diff-id=1,diff-type=compliant]
----
while (condition) { /*...*/ }
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for[`for`]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while[`while`]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]