Roller coaster

For in loop JavaScript

We often heard about JavaScript Loop For in can be sometimes problematic. We are going to show you how this statement works.

The purpose of the for in statement is to enumerate over object properties, and we should be careful using it with and Array object.

First problem we have it is order of iteration, although most of browsers iterate over properties in the same order there were defined, other do not do the same.

Even on Array objects the order of enumeration is defined as the properties were created.

Furthermore there is one more problem, for in loop not only iterate over object properties, it do it for it prototype properties too.

We can see one example about this:


If we run the example we can see the output is: monkey, elephant, tiger y test.

To avoid this problem we can use a method that checks if the object it is the owner of the property and not the prototype.

If we run this example we will not get test result.

To summarize it is safer iterate over an Array object using for or while loop instead for in.

We hope this post help you.