JavaScript for...in vs for

javascript

Solution

The choice should be based on the which idiom is best understood.

An array is iterated using:

for (var i = 0; i < a.length; i++)
   //do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
  //do stuff with o[key]

Unless you have earth shattering reasons, stick to the established pattern of usage.

Problem

Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why? Let's say we have an array of associative arrays: ``` var myArray = [{'key': 'value'}, {'key': 'value1'}]; ``` So we can iterate: ``` for (var i = 0; i < myArray.length; i++) ``` And: ``` for (var i in myArray) ``` I don't see a big difference. Are there any performance issues?

Original source