Skip to main content

prefer-for-of

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

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

Attributes

  • Included in configs
    • ✅ Recommended
    • 🔒 Strict
  • Fixable
    • 🔧 Automated Fixer
    • 🛠 Suggestion Fixer
  • 💭 Requires type information

Rule Details

For cases where the index is only used to read from the array being iterated, a for-of loop is easier to read and write.

Examples of code for this rule:

for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

Options

// .eslintrc.json
{
"rules": {
"@typescript-eslint/prefer-for-of": "warn"
}
}

This rule is not configurable.

When Not To Use It

If you transpile for browsers that do not support for-of loops, you may wish to use traditional for loops that produce more compact code.