When iterating over a string or array (or anything else with a length property), I've always used a loop like this:
var foo = [...];
var i;
for(i=0; i<foo.length; i++) {
// do something
}
However, I just encountered someone who did this:
var foo = [...];
var fooLen = foo.length;
var i;
for(i=0; i<fooLen; i++) {
// do something
}
He said he thought the ".length" was recalculating the length, thus the loop would recalculate the length of the string/array over and over, so by saving its length to a variable it would be more optimized.
I always assumed length was just a value property because of the way it's used (it's not "asdf".length(), it's "asdf".length) but is this not the case?
for (var i=0, len=foo.length; i < len; i++){}is, in my experience, a more common way of using this idea. It's neater and (I think) easier to read because it keeps the assignments within the for initialisation - of course this assumes the length of the array isn't needed prior to the start of the loop. A lot of people do this routinely; a lot of people don't do it because they don't think about it; a much smaller group of people deliberately avoid this because they don't like to try to optimise prematurely or second-guess what the JS interpreter might optimise for you.innerHtmlwhich is treated as a value but actually invokes the browser's HTML compiler when assigned to.for (var i=foo.length-1; i>=0; i--){}