1

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;
        }
      }
    }
  };
Paul D. Waite
  • 89,393
  • 53
  • 186
  • 261
dekdev
  • 4,835
  • 2
  • 25
  • 32
  • 2
    I think it ensures that `obj.length` is a number. – Paul Grime May 02 '13 at 21:51
  • possible duplicate of [Whats the significant use of Unary Plus and Minus operators?](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators) – Bergi May 02 '13 at 21:57

1 Answers1

1

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

trutheality
  • 21,548
  • 6
  • 47
  • 65