user882196 user882196 - 1 month ago 7
Javascript Question

What is more efficient in Javascript : while or for statements?

I recently got the opportunity to do looping in javascript and I was rather confused whether to use for loop or while statement.

var i = foo.length;
while(i--){

}


or

for(var i=0 ;i<=foo.length;i++){

}


I want to know from javascript guys which one is more effecient to use and under what circumstances should we use them accordingly. Is it same reason as in java or someting different.

Answer

In theory the while loop is quicker because the for loop looks up the length attribute of foo every time though the loop, but in real-world use it's going to make an immeasurably small difference.