+4  A: 

What's wrong with a good old-fashioned for loop?

for( var i = 0; i < list.length; i++ ) {
    // do something with list[i]
}

The semantics of for...in and for...each...in tend to confuse people and lead to unexpected results.

Rob
In Javascript variable resolution is late bound. In your example above you would need to resolve length every iteration of the loop. You should cache the length variable by doing for (var i=0, l=list.length;i<l;i++). Good rule of thumb is the less dots the better in JS.
steve_c
+12  A: 

Check this JavaScript loop benchmarks.

CMS
Wow, that's cool!
Plan B
@Plan B: Yeah, look this article also: http://www.moddular.org/log/javascript-loops/
CMS
Hopefully this encourages you to go with whatever is clearest--not fastest. They're all fast.
Michael Haren
@Michael: Good point
CMS
@Micheal - Yeah in my Opera the first without any optimization is often the fastest...
rkj
A: 

CMS's link should show you for small data sets they're all fast, the only thing i'd suggest is that you avoid for (a in b) as it has a much higher memory overhead than any other looping construct and can potentially be much slower due to its "interesting" semantics.

Anyhoo, with the exception of for(in) any real JS should be spending quite a bit more time actually doing real work than is spent handling the looping itself, so minor variation in cost of the loop shouldn't be too important.

olliej
A: 

This was covered recently in Greg Reimer's Weblog.

The quick answer is this:

for (var i=0, node; node = hColl[i++];) {
    // do something with node
}
nes1983
A: 

As answered elsewhere (why does this thread exist?): the reverse while:

var i = foo.length; while (i--) { /* do something with foo[i] */ }

..is the fastest loop if you can deal with the caveats that:

  • reverse order isn't always suitable

  • it's a bit hard to read

  • it adds a variable to the footprint of whatever scope it's in

  • it's only slightly faster than the smaller footprinted and more readable cached length for loop

annakata
A: 

Supposedly objects are faster... For example:

var array = {"0": "foo", "1": "bar"}
for(var i in array){
    var val = array[i];
    // do something
}
Psychcf