Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for..in or for..of Object keys

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?

like image 834
Spedwards Avatar asked Apr 17 '17 06:04

Spedwards


People also ask

What is the difference between for in and object keys?

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

What is the difference between for in and for of?

Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.

What is for of and for in?

for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.

How can you tell which key an object is in?

You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .


1 Answers

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

like image 176
Christos Avatar answered Sep 29 '22 05:09

Christos