This rule raises an issue when a traditional C-style for loop is used to iterate over an array when a for-of loop would be more appropriate.
Traditional for loops with manual index management are prone to off-by-one errors, which are among the most common bugs in software development.
These errors occur when the loop condition is incorrectly specified (like using ⇐ instead of <) or when array bounds are
miscalculated.
Modern JavaScript provides the for-of loop syntax, which eliminates the need for manual index management. This approach is:
When you need both the index and the element, you can use array.entries() with destructuring assignment, which still avoids manual
index management while providing both values.
Using traditional for loops increases the risk of off-by-one errors that can lead to:
Replace the traditional for loop with a for-of loop when you only need the array elements.
for (let index = 0; index < array.length; index++) {
const element = array[index]; // Noncompliant
console.log(element);
}
for (const element of array) {
console.log(element);
}