Lukasz
Lukasz

Reputation: 8900

W3C JavaScript for loop style

I was looking through the W3C Javascript Best Practices and I noticed that they write their for-loops in a different way.

var f = document.getElementById('mainform');
var inputs = f.getElementsByTagName('input');
for(var i=0,j=inputs.length;i<j;i++){
  if(inputs[i].className === 'mandatory' &&
     inputs[i].value === ''){
    inputs[i].className += ' error';
  }
}

They assign the inputs length value to j and then compare j with i. Instead of just directly comparing inputs.length with i. They don't do that everywhere in the guide just in some places. Is there a reason other than a preference for writing a for-loop this way?

Upvotes: 2

Views: 60

Answers (2)

Mark Reed
Mark Reed

Reputation: 95315

As I mentioned here, it's a performance thing. Referencing inputs.length would be a runtime attribute lookup in a hash table at the top of every loop iteration. Caching it in a local variable avoids that, and the results can be dramatic, especially on an interpreter that doesn't have JIT compilation.

Upvotes: 3

Tushar
Tushar

Reputation: 87203

Slight performance improvement.

Instead of reading length property from array again after each iteration, use cached version.

This will be very very small amount of time that this can be ignored for moderate sized arrays.

Upvotes: 5

Related Questions