For AI agents: the complete documentation index is available at https://rslint.rs/llms.txt, the full documentation bundle is available at https://rslint.rs/llms-full.txt, and this page is available as Markdown at https://rslint.rs/rules/typescript-eslint/prefer-for-of.md.
close

prefer-for-of

Added in v0.5.1

Configuration

PresetConfigured Value
✅ ts.configs.stylistic"error"
✅ ts.configs.stylisticTypeChecked"error"
rslint.config.ts
import { defineConfig, ts } from '@rslint/core';

export default defineConfig([
  ts.configs.recommended,
  {
    rules: {
      '@typescript-eslint/prefer-for-of': 'error',
    },
  },
]);

Rule Details

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

Many developers default to writing for (let i = 0; i < ...; i++) loops to iterate over arrays. However, in many cases the loop iterator variable is only used to access the respective element of the array. In such cases, a for-of loop is simpler and more readable.

This rule will report when a for loop can be replaced with a for-of loop.

Examples of incorrect code for this rule:

declare const array: string[];

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

Examples of correct code for this rule:

// for-of loop
for (const x of array) {
  console.log(x);
}

// Index variable is used for more than just array access
for (let i = 0; i < array.length; i++) {
  console.log(i, array[i]);
}

// Array element is being assigned
for (let i = 0; i < array.length; i++) {
  array[i] = 0;
}

Original Documentation