aked
aked

Reputation: 5815

What does +obj.length mean in Underscore.js’s each method?

I am trying to read underscore.js. I’m going through the var each = _.each = _.forEach method.

I understand strict equals (===), but I do not understand what +obj.length means.

else if (obj.length === +obj.length)

Here is a link to the code, and here is the full method:

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

Upvotes: 1

Views: 160

Answers (1)

trutheality
trutheality

Reputation: 23465

This is a unary + operator. It converts its argument to a number. Basically that line checks if obj.length is a number.

Upvotes: 1

Related Questions