0
var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }
    }
    return obj;
  };

In the implementation of _.each method in underscore.js, the loop variables are set as follows.

for (var i = 0, length = obj.length; i < length; i++)

why is the length variable explicitly declared?, isn't the following code more succinct?

for (var i = 0; i < obj.length; i++)
1
  • It's more succinct but less efficient. In the second loop you're extracting obj.length on every iteration. In the first, you're just checking against a set value. Commented Feb 21, 2014 at 7:05

1 Answer 1

2

There are a couple possible reasons to declare the separate length variable:

  1. Caching it locally in its own variable can be faster than referencing it as a property every time through the loop.

  2. In some cases, the array length may grow during the iteration and you may not want to iterate newly added elements.

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.