For Loop in JavaScript

For loops are the most used loops in any language. But there is more than one way to iterate using a for loop. These are the ways you can use the for loop in JavaScript. The advantages and disadvantages are given too.

The Old fashion way.

var arr = new Array("One","Two","Three");
for(var i=0; i<arr.length; i++) {
	var value = arr[i];
	alert(i =") "+value);
}

This is the most used and most readable version. The most obvious disadvantage of this version is highlighted above. The problem is that javascript has to look up the length of the array on every iteration. This will slow down your script a bit. But the speed difference is not noticeable in most cases. If you want to notice the difference, run the loop a couple of thousand times.

More Optimized

var len=arr.length;
for(var i=0; i<len; i++) {
	var value = arr[i];
	alert(i =") "+value);
}

This is a more optimized version of the first script - here we are caching the length of the array in a variable - so javascript will not have to find the length every time. This works only if the length of the array do not change while it is in the loop.

Reversed

for(var i=arr.length-1; i>=0; i--) {
	var value = arr[i];
	alert(i =") "+value);
}

For items where order is not important this might be a better way. Here we find the length of the array in the initialization part of the loop - so it will be executed only once. But the loop is executed in reverse - so if you want to preserve the order of the loop this method cannot be used.

In-line

This little trick will let you assign the current value and the length of the array within the for statement itself. However, this will take a huge toll in readability. If another developer who is not accustomed to this method should view the code, it will take them a while(pun unintended) to figure out what the code is for(pun intended).

Right order

for(var i=0,len=arr.length; value=arr[i], i<len; i++) {
	alert(i =") "+ value);
}

Reversed Order

for(var i=arr.length-1; value=arr[i], i>=0; i--) {
	alert(i =") "+ value);
}

Associative Arrays

All the above methods are designed for lists(numerical arrays) so you will not be able to use them for associative arrays. For iterating through a associative array, you need a special form of the for loop. Enter for in. Although this is created for iterating through an associative array, it can be used for numerical arrays too.

This is like the foreach loop provided by PHP, Perl etc. with a slight difference - the key is returned rather than the value. The variable 'i' will contain the key of the array. In the case of lists, it will have the values 0,1,2 etc.

for(var i in arr) {
	var value = arr[i];
	alert(i =") "+ value);
}

So which type do you use? Or have you abandoned for for while?

Update: The folks behind webucator has created a video based on this article. Check out their Javascript classes to see the video.

blog comments powered by Disqus