javascript object looping

February 2nd, 2009   Filed Under Good to know, Javascript, Tips & Tricks, gyan  

In javascript generally all of us must have seen the following construct.

for(i=0; i<arrayObj.length; i++)
{
// then the code
}

But more than 50% of the time you loop through some javascript object or some javascript array.

So in order to write less and convenient code, you can also write the same for in the following fashion

for(i in arrayObj)
{
//then the code
}

It pretty much does the same job of looping. The only difference is that it takes the help of the object to be looped through for looping.

And that means you cannot use this stylish construct for an artificial looping, because the for(i=0; i< ….. construct is nothing but artificial looping.

Someone will ask then how do we get the loop index. It is pretty straight forward to get the index in case of simple array. The “i” will always return the current index.


Comments

Leave a Reply