Javascript: For..In Loops Correction

Created on 26 May 2018  路  2Comments  路  Source: airbnb/javascript

For the no-restricted-syntax rule of style.js, I believe there is an incorrect statement about for..in loops.

https://github.com/airbnb/javascript/blob/2ba36de952fcb6a931471980f4fbbdc4df468baa/packages/eslint-config-airbnb-base/rules/style.js#L327

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.

question

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 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

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

progre picture progre  路  3Comments

surfaceowl picture surfaceowl  路  3Comments

stephenkingsley picture stephenkingsley  路  3Comments

ryankask picture ryankask  路  3Comments

xgqfrms-GitHub picture xgqfrms-GitHub  路  3Comments