2

Most looping examples I see in javascript use the array.length property in the for loop itself, like so:

var numbers = [1,2,3,4,5];
for (var i = 0; i < numbers.length; i++) {
  // do something
}

However, sometimes I see the array.length property being written to a variable, and then the variable value is used in the loop, instead:

var numbers = [1,2,3,4,5];
var len = numbers.length;
for (var i = 0; i < len; i++) {
  // do something
}

Coming from a C# background, I've never had to worry about this. However, in Javascript is the second method more efficient and why?

3
  • 3
    you might want to take a look at this: jsperf.com/fastest-array-loops-in-javascript/30 Commented Nov 3, 2013 at 12:30
  • thanks, that's a good link. Commented Nov 3, 2013 at 12:35
  • Note that aside from efficiency, these two differ in terms of what happens if the array changes length during the loop. Commented Nov 3, 2013 at 12:39

1 Answer 1

1

The second is more efficient because it does not have to make an operation on anything. In the first, it just has to reference a data cell each time.

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

Comments

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.