Devang Paliwal
Devang Paliwal

Reputation: 307

(obj.length === +obj.length) Whats the purpose of this + after === in underscore.js source code?

In _.each method of underscore.js source code, they have used obj.length === +obj.length. In the first else if condition. Why they have used this + operator, whats is the significance of it?

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: 3

Views: 187

Answers (3)

Rinku
Rinku

Reputation: 1078

obj.length can be any type even undefined. 
+obj.length is always a number.

So this code checks if the length property exists and is a number. The reason for this check is that _.each() accepts both arrays and non-array objects. In case of an array the length property is necessary to iterate over its elements while a for..in loop is the way to go in case of a non-array object.

Upvotes: 3

RichieHindle
RichieHindle

Reputation: 281415

The + operator converts its argument into a number. They then use the "is exactly the same as" operator === to test obj.length against the result.

What it actually means is that the test will only succeed if obj.length is a number, rather than (for example) the string "3".

Upvotes: 6

Mark Rushakoff
Mark Rushakoff

Reputation: 258138

The unary + operator will coerce a string to a number so that the faster === operator may be used against the left-hand argument which is known to be a number.

e.g.

s = "123";
i = 123;

i === s; // false
i === +s; // true

Upvotes: 3

Related Questions