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?
I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native
Array
withfor in
structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.
I would use
for in
to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.
The two are not the same when the array is sparse.
here is something i did.
this is how you would use it
this will work on arrays and objects( such as a list of HTML elements )
I just made this so I'm open to suggestions :)
If you really want to speed up your code, what about that?
it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter
there are performance differences depending on what kind of loop you use and on what browser.
For instance:
is almost twice as fast on some browsers than:
However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)
For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.
http://www.prototypejs.org/api/array