Wrap the body of a for-in loop in an if statement with a hasOwnProperty guard
14 white: "\x1b[37m"
15 };
16
17 for (const key in colors) {18 // Each color method calls console.log with the color as the first argument,followed by any additional arguments.19 Logger.prototype[key] = function(...args) {20 console.log(colors[key], ...args);21 };22 }23 }
24}
25
Description
Looping over objects with a for in
loop will include properties that are inherited through the prototype chain.
This behavior can lead to unexpected keys in your for loop.
Bad Practice
for (const key in foo) {
doSomething(key);
}
Recommended
for (const key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
for (const key of Object.keys(foo)) {
doSomething(key);
}