2

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?

1
  • 2
    caching length increases loop performance Commented May 17, 2016 at 15:16

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

I believe, this case is even worse: browser will query DOM for each iteration because the collection could have been changed since previous step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.