Substitute for the for loop
March 26th, 2008 Filed Under Good to know, Javascript, comparisons, gyan
Today I came to know a new trick of looping collections. Generally we do a for loop and have i or any other variable as the counter. An alternative to this could be something like this:
var ar = [0,1,2,3,4]; //array
while(ar.length != 0)
{
document.write(ar[0]);
ar.shift();
} //displays 01234
If you have a set of nested for loops which in turn calls other functions which has some loop, and if the counter variable name is same then some browsers forget the scope and reinitializes the variable or shows up the latest value that was set by the latest loop before it lands back to the host loop.
This while construct can save you some lines as well as risk of i(can i call it i-risk? like i-pod???)
Isn’t it Good to know !!
Post Linx
Permalink | Trackback |
|
Print This Article |
Comments
Leave a Reply

