Yeonho
Yeonho

Reputation: 3623

loop variable declaration style in for loop

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++)

Upvotes: 0

Views: 59

Answers (1)

jfriend00
jfriend00

Reputation: 707318

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.

Upvotes: 3

Related Questions