src/content/docs/linter/rules/no-for-in.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> :::caution This rule is part of the [nursery](/linter/#nursery) group. This means that it is experimental and the behavior can change at any time. ::: ## Summary - Rule available since: `v2.3.6` - Diagnostic Category: [`lint/nursery/noForIn`](/reference/diagnostics#diagnostic-category) - This rule doesn't have a fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Inspired from [`@typescript-eslint/no-for-in-array`](https://typescript-eslint.io/rules/no-for-in-array){
"linter": {
"rules": {
"nursery": {
"noForIn": "error"
}
}
}
}
Disallow iterating using a for-in loop.
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:
RegExp.prototype.exec returns an array with additional properties, and for-in will iterate over them. Some libraries or even your own code may add additional methods to Array.prototype (either as polyfill or as custom methods), and if not done properly, they may be iterated over as well.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.
for (const i in array) {
console.log(i, array[i]);
}
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);
}