Logical Looping

As sad as it is, this is the fifth and final installment in my series 5 Things Everyone Could Learn from The jQuery Source. Please feel free to comment!

5) Logical Looping

How many times have you seen or written the following code:

for (x=0;x<y.length;x++) {

We’ve all done it, it’s a sin we’ve all committed at one point or another. These loops are a hallmark of a sloppy code. Many people go on to that next level, and optimize this loop like this:

var l = y.length;
for ( x=0; x < l; x++) {

This is a form of caching (discussed above). The huge win here, obviously, is that you only have to compute the length of ‘y’ once, instead of once every time the loop runs. The jQuery source takes this one step further, so that again the semantics of the code are improved, leaving you no doubt as to the fact that the loop you’re reading is highly efficient and optimized. Here is an example from lines 921-930 in the code:

indexOf = arr.indexOf || function( elem ) {
	var i = 0,
	    len = this.length;
	for ( ; i < len; i++ ) {
		if ( this[i] === elem ) {
			return i;
	return -1;

As you can see, the variables i and len are both declared before the for loop. And the big win here is that the length here is computed only once, which is efficient. Another trick that is used here is that you will notice that there is no ‘first’ element in the for() syntax. This is because i has already been instantiated before the loop so we do not need to declare it in the for() syntax. By going back and reconstructing our own for loops to match this syntax, we can make our code several levels better than it was before.

And ultimately, that’s what it’s all about, right? Writing better code. Let’s face it, if we want to make the web a better place, we have to get better at writing better code.

I hope you’ve enjoyed this series on learning from the jQuery source. Feel free to leave comments on any of the posts with your thoughts on other series like this that you would enjoy.

Published 8 Feb 2011

Writing better code by building better JavaScript
Don Burks on Twitter