# guard-for-in

> Require the body of a `for...in` loop to be guarded by an `if`

`for...in` visits an object's own enumerable properties and the ones it inherits from its prototype chain. If anything was added to a prototype, the loop body runs for keys the object itself doesn't have.

The rule only looks at the shape of the loop. The body must be a single `if`, or start with an `if` that does nothing but `continue`. The rule doesn't check what the condition tests.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"guard-for-in" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
for (const key in settings) {
  apply(key, settings[key]);
}
```

{/* bad */}
```js
for (const key in settings) {
  if (Object.hasOwn(settings, key)) {
    apply(key, settings[key]);
  }
  count++;
}
```

Not reported:

{/* good */}
```js
for (const key in settings) {
  if (Object.hasOwn(settings, key)) {
    apply(key, settings[key]);
  }
}

for (const key in settings) {
  if (!Object.hasOwn(settings, key)) continue;
  apply(key, settings[key]);
  count++;
}
```

`Object.keys()` returns only the object's own keys, so a `for...of` loop over it doesn't need a guard:

{/* good */}
```js
for (const key of Object.keys(settings)) {
  apply(key, settings[key]);
}
```
