no-for-in-array
Disallow iterating over an array with a for-in loop.
Extending "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
This rule requires type information to run.
A for-in loop (for (const i in o)
) iterates over the properties of an Object.
While it is legal to use for-in loops with array values, it is not common. There are several potential bugs with this:
- It iterates over all enumerable properties, including non-index ones and the entire prototype chain. For example,
RegExp.prototype.exec
returns an array with additional properties, andfor-in
will iterate over them. Some libraries or even your own code may add additional methods toArray.prototype
(either as polyfill or as custom methods), and if not done properly, they may be iterated over as well. - It skips holes in the array. While sparse arrays are rare and advised against, they are still possible and your code should be able to handle them.
- The "index" is returned as a string, not a number. This can be caught by TypeScript, but can still lead to subtle bugs.
You may have confused for-in with for-of, which iterates over the elements of the array. If you actually need the index, use a regular for
loop or the forEach
method.
module.exports = {
"rules": {
"@typescript-eslint/no-for-in-array": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
declare const array: string[];
for (const i in array) {
console.log(array[i]);
}
for (const i in array) {
console.log(i, array[i]);
}
Open in Playgrounddeclare const array: string[];
for (const value of array) {
console.log(value);
}
for (let i = 0; i < array.length; i += 1) {
console.log(i, array[i]);
}
array.forEach((value, i) => {
console.log(i, value);
});
for (const [i, value] of array.entries()) {
console.log(i, value);
}
Open in PlaygroundOptions
This rule is not configurable.
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 ESLint disable comments for those specific situations instead of completely disabling this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.