For the no-restricted-syntax rule of style.js, I believe there is an incorrect statement about for..in loops.
The message states that "for..in loops iterate over the entire prototype chain", while they actually only iterate over the enumerable properties. Object.keys returns the keys of the enumerable properties of the object, so the end behavior of using this is the same.
Given this, would you still discourage using for..in loops? I can't see anything wrong with them, besides personal preference for using array methods vs loops.
They do indeed iterate over the entire prototype chain - iow, over each single object in the prototype chain. They also only enumerate the enumerable properties. Object.keys only returns own enumerable properties; for..in returns inherited ones as well.
So yes, for..in loops are terrible and should never be used when avoidable.
One (admittedly unlikely) example is, Object.prototype.foo = true is enough code to break all of your for..in loops, potentially.
@ljharb - thanks for explaining that! For some reason I wasn't seeing that behavior with examples I was testing (like a new object won't print hasOwnProperty in for..in loop for example, I guess that isn't an enumerable property).
I can clearly see undesired behavior when setting Object.prototype.foo so it makes sense for..in should be avoided. Thanks again.
Here's a good link showing the difference if anyone stumbles across this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
Most helpful comment
@ljharb - thanks for explaining that! For some reason I wasn't seeing that behavior with examples I was testing (like a new object won't print
hasOwnPropertyinfor..inloop for example, I guess that isn't an enumerable property).I can clearly see undesired behavior when setting
Object.prototype.fooso it makes sensefor..inshould be avoided. Thanks again.Here's a good link showing the difference if anyone stumbles across this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties