The analyzer has detected a nested for loop whose counter is initialized with the value of the outer loop's counter. Such code often contains a bug: most likely, the iteration should start from the next element, i + 1.
The example:
function hasDuplicates(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
if (arr[i] === arr[j])
return true;
}
}
return false;
}
The function should check whether an array contains duplicate elements, but because the inner loop that starts with j = i, each element is compared with itself on the first iteration. Since arr[i] === arr[i] is always true, the function returns true for any non-empty array.
The fixed code:
function hasDuplicates(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j])
return true;
}
}
return false;
}
The analyzer also issues a warning:
function hasDuplicates(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
if (i !== j && arr[i] === arr[j])
return true;
}
}
return false;
}
In this case, the i !== j is checked on every iteration, even though it only filters out a single one. The extra iteration is redundant, and the extra branch complicates loop optimization for the compiler.
This diagnostic rule is classified as:
Was this page helpful?