For .. in or for ... object keys

So my IDE doesn't like it when I use a for..in loop to iterate over object keys. I am getting a warning:

Possible iteration over unexpected (user / inherited) members, possibly missing hasOwnProperty check

So, I understand what he is saying, so in such a case it is better to use something like for (const key of Object.keys(obj))

instead of for (const key in obj)

?

Are there any real differences between the two, in terms of performance?

+3


source to share


2 answers


There is a slight difference between loops using an array Object.keys

and loops using an operator for...in

, which will not be checked in most cases. Object.keys(obj)

only returns an array with its own object properties, while it for...in

also returns the keys found in the prototype chain so that the latter is executed, additional prototype checking is obj

needed and then the prototype prototype, etc. and so on until the whole prototype chain is shown. This certainly makes the second approach less efficient than the first, but as I mentioned, this difference is unlikely to be noticed in most cases.

For a more formal approach, as stated on MDN :



The Object.keys () method returns an array of a specific object with enumerable properties, in the same order as the for ... in loop (the difference is that the for-in loop enumerates properties in the prototype chain).

+3


source


You can use for(var key in obj){}

. It seems to be waiting Object.hasOwnProperty

inside a loopfor..in

This is because it for..in

will also appear on the prototype chain and will return true even if the key is on the prototype chain.

Whereas it Object.hasOwnProperty

only returns true if the key is a property owns

.



You can do it

for(var key in obj){
 if(obj.hasOwnProperty(key){
  // rest of code}
}

      

+2


source







All Articles