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.
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.
In some browsers some ways of looping are faster - for example, in Chrome, the for
loop is more than twice as fast, but there is no consistent winner across all browsers. If you find a trick to make it really fast in one browser, you will be punished for it in another browser.
Actual performance test in different browsers: http://jsperf.com/for-or-while
You should use the type of loop that makes sense for the situation. In many cases what you do inside the loop takes a lot longer than the loop itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With