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.
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.
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... inwill actively iterate over own enumerable properties of theObjectfrom 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 duringfor..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.