I recently came accross a different way of looping though an array in Javascript.
I used to write loops something like this:
for (var len = 0; len < testData.length; len++) {
total = total + testData[len];
}
I read some code that did it this way:
for (var len = 0; testData[len]; len++) {
total = total + testData[len];
}
I was wondering how these would perform so I used jsPerf to find it out. The results are pretty amazing. I expected the second method to be a bit it faster than the first, but it's actually much, much faster.
Is there a down side I'm missing here? Or is this the best way to loop through the items of a list.
Update:
gray state is coming and Diode pointed me to a simple flaw in the testcase which made is seem to be faster.
After correcting the mistake, this is the fastest:
var datalen = testData.length;
for (var len = 0; len <datalen; len++) {
total = total + testData[len];
}
Update 2:
After testing in some more browsers this testcase takes a different direction again. Only in Chrome and Opera the normal for loop is the fastest. In other all other browsers Shmiddty's way is just a bit faster.
var i = testData.length, sum=0;
while (i--){
sum += testData[i];
}