for-in
loops should include an if
statement JS-005114 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
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.
for (const key in foo) {
doSomething(key);
}
for (const key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
for (const key of Object.keys(foo)) {
doSomething(key);
}