Skip to content

forInGuards

Reports for-in loops without an if statement to filter inherited properties.

✅ This rule is included in the ts preset.

Looping over objects with a for-in loop will include properties inherited through the prototype chain. This can lead to unexpected items being iterated over when the object inherits from a non-standard prototype.

for (const key in object) {
doSomething(key);
}
for (const key in object) {
doSomething(key);
}
for (const key in object) {
if (condition) {
doSomething(key);
}
doSomethingElse(key);
}

This rule is not configurable.

If you are certain that the objects you iterate over do not have inherited properties from custom prototypes, you might choose to disable this rule. This is common when iterating over plain objects created with object literals or Object.create(null).

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.