src/content/docs/linter/rules/use-guard-for-in.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.9.4` - Diagnostic Category: [`lint/suspicious/useGuardForIn`](/reference/diagnostics#diagnostic-category) - This rule isn't recommended, so you need to enable it. - This rule doesn't have a fix. - The default severity of this rule is [**warning**](/reference/diagnostics#warning). - Sources: - Same as [`guard-for-in`](https://eslint.org/docs/latest/rules/guard-for-in){
"linter": {
"rules": {
"suspicious": {
"useGuardForIn": "error"
}
}
}
}
Require for-in loops to include an if statement.
Looping over objects with a for-in loop will include properties inherited through the prototype chain.
This behavior can lead to unexpected items in your for loop.
For codebases that do not support ES2022, Object.prototype.hasOwnProperty.call(foo, key) can be used as a check that the property is not inherited.
For codebases that do support ES2022, Object.hasOwn(foo, key) can be used as a shorter and more reliable alternative.
for (key in foo) {
doSomething(key);
}
for (key in foo) {
if (Object.hasOwn(foo, key)) {
doSomething(key);
}
}
for (key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
for (key in foo) {
if ({}.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}