forInArrays
Reports iterating over an array with a for-in loop.
✅ This rule is included in the ts logical
preset.
A for-in loop (for (const i in o)
) iterates over all enumerable properties of an object, including those that are not array indices.
This can lead to unexpected behavior when used with arrays, as it may include properties that are not part of the array’s numeric indices.
It also returns the index key (i
) as a string, which is not the expected numeric type for array indices.
Consider using a construct more suited for arrays, such as a for-of loop (for (const i of o)
).
Examples
Section titled “Examples”const values = ["a", "b", "c"];
for (const key in values) { console.log(values[key]);}
const values = ["a", "b", "c"];
for (const value of values) { console.log(value);}
Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If your project is a rare one that intentionally loops over string indices of arrays, you can turn off this rule. You might consider using Flint disable comments and/or configuration file disables for those specific situations instead of completely disabling this rule.
Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
@typescript-eslint/no-for-in-array
- Oxlint:
typescript/no-for-in-array