While reading through the JavaScript Patterns book, I saw an item that totally stuck out as a crystal clear “duuhhh!!” moment. Why have I never seen/heard of that before and certainly why wasn’t I doing it regularly (and why hadn’t I thought of it to be honest).
Instead of doing this:
[sourcecode lang=”javascript”]
for(var i=0; i < $(‘someselector li’).length; i++){
//loop through each LI in a UL, or any collection
//do work…
}
[/sourcecode]
Pre-cache the length instead, so you arent making extra calls to jQuery every time to have the length computed (for every cycle in the for loop!):
[sourcecode lang=”javascript”]
for(var i=0, var max=$(‘someselector li’).length; i < max; i+=1){
//loop through each LI in a UL, or any collection
//do work…
}
[/sourcecode]
As long as you aren’t actually messing with the items in the collection which would cause length to change, this method works perfectly fine and only does the extra work of computing length (max) once! (Also note the use of +=1 instead of ++ – JSLint prefers it this way.)