Don’t Use for…in With JavaScript Arrays!

Don’t use the for...in statement to iterate over JavaScript arrays because the result might not be what you were expecting. Read on to find out the correct way to iterate over a JavaScript array.

How Do You Loop Over an Array in JavaScript?

Not being much of a JavaScript developer, I found myself looking up how I should loop over an array. I really just wanted to see whether there was a foreach (myArray as item) syntax simlar to PHP. I quickly spotted some code that looked about right:

for(x in y){// Do something with x}

for (x in y) {
// Do something with x
}

Simple! Only it didn’t work. When I ran the code I found that my array inexplicably contained additional properties.

for(x in y) Should Only Be Used For Object Properties

Using for(x in y) on an array will iterate over any enumerable properties, including ones added by old JavaScript frameworks, and consequently all your arrays can appear to have extra properties.

It turns out that I had been using one such old JavaScript framework, which had extended Array.prototype and I had blindly used some code that “looked right”, without noticing that it was meant to be used for iterating over an object’s properties, not an array’s.

How to Correctly Iterate Over an Array

The correct way to iterate over an array in JavaScript, according to Mozilla is: