A loop is a control structure that allows a block of code to be executed repeatedly until a certain condition is met. The basic idea behind a loop
is to automate repetitive tasks, such as iterating over a collection of data or performing a calculation multiple times with different inputs.
An infinite loop is a loop that runs indefinitely without ever terminating. In other words, the loop condition is always true, and the loop never
exits. This can happen when the loop condition is not defined or when the loop condition is never met.
Infinite loops can cause a program to hang or crash, as the program will continue to execute the loop indefinitely.
This rule will raise an issue on for
, while
and do...while
loops where no clear exit condition has been
found.
There are some known limitations for this rule:
- False positives: when an exception is raised by a function invoked within the loop.
- False negatives: when a loop condition is based on an element of an array or object.
for (;;) { // Noncompliant: end condition omitted
// ...
}
let j = 0;
while (true) { // Noncompliant: constant end condition
j++;
}
let k;
let b = true;
while (b) { // Noncompliant: constant end condition
k++;
}
Ensure the loop condition is defined or use a break
statement.
for (let i = 0; i < 5; i++) {
// ...
}
let j = 0;
while (true) {
j++;
if (j < 5) {
break;
}
}
let k;
let b = true;
while (b) {
k++;
b = k < 10;
}