for..in or for..of Object keys
Asked Answered
S

2

14

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

Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check

So I get what it's saying, so in that case would it be 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, performance-wise?

Sunglasses answered 17/4, 2017 at 6:23 Comment(3)
what your IDE wants is sanity check you should put in your code if(obj.hasOwnProperty(key)) {.. your code }Leonidaleonidas
This might help you #29004814Infective
Possible duplicate of Why are Object.keys() and for ... in different?Charo
P
25

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

Position answered 17/4, 2017 at 6:30 Comment(1)
Thanks. This explains why my IDE was giving the warning.Sunglasses
S
5

You can still use for(var key in obj){}. It seems it is expecting is Object.hasOwnProperty inside the for..in loop

This is because for..in will also look in prototype chain & will return true even if the key is in prototype chain.

Whereas Object.hasOwnProperty will only return true if key is its owns property.

You may do like this

for(var key in obj){
 if(obj.hasOwnProperty(key)){
  // rest of code}
}
Samuel answered 17/4, 2017 at 6:32 Comment(1)
At this point though, you might as well just use the Object.keys(obj) implementation. Since the only thing you're avoiding is prototype keys (which is what Object.keys already does).Hemianopsia

© 2022 - 2024 — McMap. All rights reserved.