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?

Comments

Sujith Joshy at 26 Jun, 2008 11:45
Hi Binny,

Sujith Here...

One question, IS there any Build in Function in Javascript to sort an array with respect to the key. as like ksort in PHP.
Or How will we do this in Javascript.

if you have the solution for this, please email to me @ sujith.joshy@itcinfotech.com


Regards
Sujith joshy
Reply to this.
Gigan at 03 Oct, 2008 07:49
One interesting thing I just discovered in the different for loops types is that your "old fashioned" for loops use an integer as an iterator, whereas the associative arrays use the value of the iterator as a string.

Thus
for(var i=0; i<array.length; i++) alert(i + 5);
would display 5, 6, 7, etc.

however
for( var i in array ) alert(i + 5);
would display 05, 15, 25, etc.
Reply to this.
Binny V A at 03 Oct, 2008 10:43
Do this...
alert(Number(i) + 5);

The 'for in' loop makes 'i' a string.
Reply to this.
Daniel at 22 Oct, 2008 01:00
In your in-line example, I think you can optimise it even further:


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


As you mention, it might not be as readable but it is efficient.
Reply to this.
Jaka Jancar at 21 Nov, 2008 11:19
Won't work if value evaluates to false though.
Reply to this.
Vishalkumar at 04 Aug, 2009 07:02
var lArray = new Array("Z","B","C");
lArray.sort();
alert(lArray);
Reply to this.
Snowfarthing at 06 Aug, 2009 10:26
I just wanted to point out that the "for" loop isn't the most used in *every* language. In Haskell, the most-used loop is recursion (it's an interesting challenge to write a matrix routine using only recursion!) and in Lisp, the most common loop is called "loop", although recursion is also extremely popular in Lisp, too.

I'd imagine that it's similar for other functional languages, like ML and Erlang...

Also, in Assembler languages (at least, those not corrupted by higher-level thinking...), the most common loop construct is something like

label1:
CMP A1, A2
JMPZ label2
...do stuff
JMP label1
label2:
...continue on...
Reply to this.
Vipin Cherukara at 15 Sep, 2009 04:24
For javascript tutorials , examples and sample codes
javascriptfactory.blogspot.com/
Reply to this.
Vinny at 16 Sep, 2009 03:04
this loop seems to count up for me, i want it to count down.

for(var i = 30; i >= 0; i--) {
document.write(i);
}
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.