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.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"guard-for-in" = "error" # or "warn"Examples#
example.js1 problem
for (const key in settings) {The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.
apply(key, settings[key]);
}example.js1 problem
for (const key in settings) {The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.
if (Object.hasOwn(settings, key)) {
apply(key, settings[key]);
}
count++;
}example.jsNo problems
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:
example.jsNo problems
for (const key of Object.keys(settings)) {
apply(key, settings[key]);
}