5

I just read the underscope source code, and cannot get the point from this code:

_.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    iterator = createCallback(iterator, context);
    var i, length = obj.length;
    if (length === +length) {   // why +length?
        for (i = 0; i < length; i++) {
            iterator(obj[i], i, obj);
        }
    } else {
        var keys = _.keys(obj);
        for (i = 0, length = keys.length; i < length; i++) {
            iterator(obj[keys[i]], keys[i], obj);
        }
    }
    return obj;
};

why length===+length ? I guess this used for force to convert if length is not a number? Could somebody give me a hand?

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31
  • There was an exact duplicate, it's even related to the exact same code : http://stackoverflow.com/questions/8330499/operator-before-expression-in-javascript-what-does-it-do – Denys Séguret Jul 24 '14 at 07:14

2 Answers2

5

+length is a method to convert anything to a number.

If it's a number, the value doesn't change, and the comparison returns true. If it's not a number, the assertion is false.

What is unary + used for in Javascript?

Community
  • 1
  • 1
StingRay21
  • 342
  • 5
  • 15
2

+length converts any value of length to a number (NaN if not possible).

So length===+length just tests that length is really a number (not a string that could be converted to a number), and that it's not NaN (which isn't equal to itself).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758