There is a slight difference between looping though the Object.keys
array and looping using a for...in
statement, which in the majority of cases would not be noted. Object.keys(obj)
returns only an array with the own properties of the object, while the for...in
returns also the keys found in the prototype chain, in order the latter to be done extra check to the prototype of the obj
is needed and then to the prototype of the prototype and so on and so forth, until the whole prototype chain has been visited. This certainly makes the second approach less efficient than the first, but as I have already mentioned, this difference would be hardly noticed in the majority of cases.
For a more formal approach, as it is stated in the MDN:
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
if(obj.hasOwnProperty(key)) {.. your code }
– Leonidaleonidas