This Week in Patterns (TWiP) Tips is an initiative to keep me blogging regularly. From time to time I will post patterns that I currently use or new patterns that I come across.
While simple in nature, JavaScript for loops are a staple of the language. Rarely do I write any decent length script where I don’t need to iterate over a collection or an array. But when the time comes, its how you iterate that is important.
Luckily it’s simple and quickly becomes second nature. Here’s the vanilla method for doing a standard for loop:
var someArray = [];
// items added 'mysteriously' to someArray
for (var i = 0; i < someArray.length; i++) {
// do something with someArray[i]
}
The unfortunate side effect of this, is that each iteration someArray.length has to be looked up. You’re probably saying to yourself…”Let’s ‘cache’ that puppy.” If that’s what you said, well, you’re right!
var someArray = [];
// items added 'mysteriously' to someArray
for (var i = 0, len = someArray.length; i < len; i++) {
// do something with someArray[i]
}
That’s all there is to it. Although, I’d like to point out that for small arrays, the performance gain from the second option isn’t going to make any noticeable difference but it’s still good practice. With that said however, if you use the same method above for iterating over HTMLCollections you see quite a bit of difference the larger the collection, depending on the browser.
Example with HTML Collection
var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++) {
// do something with divs[i]
}
Taking it further
While this isn’t something I do all that often, I still think it’s important to point out, due to the fact that JSLint will hurt your feelings over it.
This pattern removes the ‘excessive trickiness’ (whatever that means) from the incrementing i variable.
var someArray = [];
// items added 'mysteriously' to someArray
for (var i = 0, len = someArray.length; i < len; i += 1) {
// do something with someArray[i]
}
The benefit that this option does have, is that you can quickly change the increment from 1 to whatever with relative ease. I still think it’s a personal choice, however.
