Skip to main content

prefer-for-of

Enforce the use of for-of loop over the standard for loop where possible.

🎨

Extending "plugin:@typescript-eslint/stylistic" in an ESLint configuration enables this rule.

Many developers default to writing for (let i = 0; i < ... loops to iterate over arrays. However, in many of those arrays, the loop iterator variable (e.g. i) is only used to access the respective element of the array. In those cases, a for-of loop is easier to read and write.

This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-for-of": "error"
}
};

Try this rule in the playground ↗

Examples

declare const array: string[];

for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
Open in Playground

Options

This rule is not configurable.

Resources