r/javascript • • Oct 14 '16

help Object.keys vs. for...in, which do you prefer and which is more performant?

1 Upvotes

15 comments sorted by

View all comments

1

u/ttolonen Oct 14 '16

They are different animals: Object.keys just returns Object's own enumerable, not-inherited properties in an Array. for... in will actively iterate over own enumerable properties of the Object from the full prototype chain as they currently are, which includes inherited properties and possibly changes to object during the loop. That means hard to spot bugs can be created, if the keys are added or deleted during for..in -loop. In this sense it is usually safer to first get the keys with Object.keys and then iterate over Object using that result.

1

u/[deleted] Oct 15 '16

[removed] — view removed comment

0

u/ttolonen Oct 15 '16

The performance difference is not significant, and they do different things, so no reason to compare unless you know the data and what should be done with it.