Let’s declare the following array and then try to iterate over it.
The most common way of doing this is with a simple for loop.
You can also use the each method in jQuery.
The downside here is that we’re declaring a new function and changing the context – the meaning of the keyword this will change – something which can get a bit annoying at times.
The default for loop is also a bit inefficient – you are looking up the length property on every loop. A slight improvement is this:
An even nicer way is this:
Although I’m not crazy about the index moving on before you can use it. I think the easiest way is probably:
Interestingly enough if you add properties to Array.prototype they will also be iterated in this way. While this is probably the easiest way to iterate over an array it’s also very inefficient – up to 20 times slower than a standard for loop. Read more here.
So the best way of iterating over an array is probably a standard for loop where we cache the length property. (Leaving out the caching may result in the loop being only half as fast as with the cached length)