5

I always use for (i=0; i<array.length; i++) when looping through arrays.

I always use for (var i in object) when looping through object properties.

I can't use for (i=0; ... ) for object properties, but I can use for (var in ...) for arrays, because arrays are objects too.

The question I ask is: should I dump for (i=0; ... ) completely and use for (var in ...) for both arrays and objects? Is there a performance hit? Why would I use one over the other?

Jared
  • 2,978
  • 4
  • 26
  • 45
  • 5
    This is pretty much a dup, or at least strongly related to, [an S.O. question viewed over 160K times](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea). – Ray Toal Jun 19 '13 at 02:11
  • @RayToal I agree. The "related questions" system here is good, but not good enough it seems. :) – Jared Jun 19 '13 at 02:13
  • _However_ one thing I am concerned about that the other question didn't bring up: **performance**. – Jared Jun 19 '13 at 02:14
  • Agreed. It is very hard to know when the questions are nearly the same. However, the one I linked to should have some very good reasons for the practice of avoiding for-in for arrays and so should be helpful to you. Good point about the performance aspect not being covered though! – Ray Toal Jun 19 '13 at 02:14
  • @RayToal I definitely agree. Thanks for the link. – Jared Jun 19 '13 at 02:15
  • 1
    Actually performance is addressed in one of the comments linking to [this article](http://vocamus.net/dave/?p=1205) :) – zsawyer Jun 19 '13 at 02:24
  • @zsawyer Your eyes are better than mine. Thanks! :) – Jared Jun 19 '13 at 02:28

5 Answers5

2

should I dump for

You shouldn't. for..in when used to loop arrays doesn't care about the index and it will list properties attached to the object as well. Stick to for for arrays and for..in for objects.

An excerpt from the MDN:

for..in should not be used to iterate over an Array where index order is important... There is no guarantee that for..in will return the indexes in any particular order and it will return all enumerable properties...

As for the performance, I wouldn't worry about it, because for..in to loop indexed arrays is obviously not recommended.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
2

I made a jsperf for you :

http://jsperf.com/for-vs-for-in43

Basicly, it is testing perfomance and you can see a huge performance drop when using for(var i in array).

That being said, you souldn't drop the forfor for in.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

can't use for (i=0; ... ) for object properties, but I can use for (var in ...) for arrays, because arrays are objects too.

You should use for as the other answers already state.

But you can use Object.keys(yourObject) to list the object's keys as an array, then use the for loop on that array.

var keys = Object.keys(myObject);
for(var i = 0, key; key = keys[i]; i++) {
    //...
}
  • Although I'm hesitant to use it because of browser support, this sounds like a great way of doing it. +1 – Jared Jun 19 '13 at 02:29
  • @Jared true, although the support is pretty good excluding older IE and Opera: http://kangax.github.io/es5-compat-table/ –  Jun 19 '13 at 03:17
  • 1
    I'm counting down the days until I can stop supporting IE8. – Jared Jun 19 '13 at 03:34
1

If you want to have a fast responsive code then:

for arrays the while( l--) and the for(i=0,..) loops are the fastest one...

in object arrays you can only use for in... but if your code is good it does no happen very often that you loop through an object.

fastest loops:

var myarray=[1,2,3,4,5,6],
length=myarray.length;//here i cache the length of the array.

caching the array length is another important thing to keep the code fast.

while(length--){
//do somethingwith your array
 //myarray[length];
}

while was the fastest loop in older browsers .. in new browsers it looks like the for loop is a little faster.

for(var i=0;i<length;i++){
//do somethingwith your array
//myarray[i];
}

now if u wanna define variables, do that before you loop.

there is also a nice comparsion that shows you the performance even if sometimes the code is not written very well.

http://jsperf.com/fors-vs-while/61

so if you plan to loop through an array always use while-- or for(var i=0..) caching the length.

another loop that i really like if u have arrays in multidimensional objects like json is this one

for(var a=0,b;b=my.very.long.object[a];++a){
//do somethingwith your array 
//b
}

another mistake that most ppl do is they use push in a loop... executing push in a loop means u executea new function every time. as we already have "i" that is a index we can set that and use it to store the data directly without executing a new function

so

//wrong
for(var i=0,newArray=[];i<length;i++){
newArray.push(myarray[i]);//this is a waste of time and resources
}
//right
for(var i=0,newArray=[];i<length;i++){
newArray[i]=myarray[i];//we already have an index.
}

ps.:feel free to correct my bad english but don't touch the code!.

cocco
  • 16,442
  • 7
  • 62
  • 77
0

Note also that the order of enumeration is not guaranteed, so for..in on an array may return values out of sequence. It will also list all properties, including those that are not numeric (i.e. would not be returned by iterating over an index) and enumerable properties on the object's [[Prototype]] chain, so you must always use it with a hasOwnProperty test if you only want own properties (the most common case).

If you're using an ES5 host, then you have methods like Object.getOwnPropertyNames and Object.keys to get own properties. But again, order is not guaranteed.

Lastly, for, do and while loops are highly optimised, there is very little difference in performance and what is faster in one browser may be slow in another. Just use what suits and optimise only if performance is an issue.

RobG
  • 142,382
  • 31
  • 172
  • 209