0

What is the difference if I use one of the following to iterate javascript arrays:

for (var i = 0 ; i <abc.length :i++)  

or

for (var i in abc.lengh)

Thank you.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
Gendaful
  • 5,522
  • 11
  • 57
  • 76

2 Answers2

2

For iterating the elements of an array, you should use this form:

var x = [1,2,3,4];

for (var i = 0, len = x.length; i < len; i++) {
    // code here to access x[i]
}

For iterating the properties of an object, you should use this:

var house = {size: 3200, bedrooms: 5, garage: 2, color: "white", city: "San Francisco"};

for (var key in house) {
    // access each property here as house[key]
}

Though you can sometimes get away with using the second syntax on an array, you are asking for trouble because it will include custom properties that have been added to the array that are not array elements themselves and that can really confuse the code and lead to subtle or not-so-subtle bugs.

The addition of the len variable in the first syntax is a speed optimization because fetching the length one into a local variable can be significantly faster than accessing the length property on every iteration of the loop. It is not required to do it this way. It can be done as this also:

for (var i = 0; i < x.length; i++)
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks jFriend. If I want to access garage, then how should I access it? – Gendaful Dec 16 '11 at 00:46
  • @user515990 - You would use `house.garage`. We would all appreciate it if you would change your user name to a meaningful moniker that we'd have a chance of remembering if our paths cross again. – jfriend00 Dec 16 '11 at 00:47
  • I should add that the first method will allow you to iterate through the array elements in order. The second method has no guaranteed order. – jfriend00 Dec 16 '11 at 00:51
  • Thank you. By the way, I hve given my profileId a meaningful name :) – Gendaful Dec 16 '11 at 00:51
  • @HPK - Yeah! One less pseudo-anonymous userxxxxx name. – jfriend00 Dec 16 '11 at 00:52
1

The first example (a 'for' loop) will iterate through the elements of an array and is the preferred method of looping through an array.

The latter method (a 'for...in' loop) will iterate through all the properties of an object and is typically more useful for more complex objects than arrays. If you've added any custom properties to the array object, the for...in loop will iterate through them as well, which isn't always desired.

One more thing to keep in mind with for...in loops - they may (depending on browser) not iterate through the object in the order you expect. For more on that, see this answer to another question: https://stackoverflow.com/a/280861/726326

Community
  • 1
  • 1
Dave
  • 1,831
  • 2
  • 11
  • 5