Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negative object length possible in JavaScript or underscore.js? meaning?

I was looking at the source code for the Underscore.js library, specifically for the map method (around line 85 on that page, and copied here):

  _.map = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    if (obj.length === +obj.length) results.length = obj.length;
    return results;
  };

completely straightforward EXCEPT for the following line

    if (obj.length === +obj.length) results.length = obj.length;

Now, I read this to mean "if the object length is not a negative number..."
which, if my interpretation is right, implies that it might be!

So, dear experts, for what kinds of objects might

    obj.length === +obj.length 

be false? My understanding of === means it could return false if the type of obj.length didn't match the type of +obj.length, but here my knowledge falls short. What kinds of things could + do to the kinds of things that obj.length might be? Is x === +x some sort of generic idiomatic test that I just don't know? Is it response to some sort of special case that arises deeper in underscore.js, e.g., does underscore.js assign and track negative object.lengths for some conventional purpose? Guidance and advice will be much appreciated.

like image 972
Reb.Cabin Avatar asked Jan 09 '12 02:01

Reb.Cabin


2 Answers

I think that's testing to see if typeof obj.length === 'number'

As opposed to if it's an object that has a length value of '2 days'

So it knows if it's an object like:

var obj = { app: 'doctor', length: '45 min' };

vs

var obj = [ 0, 2, 1];
like image 79
qwertymk Avatar answered Nov 08 '22 10:11

qwertymk


In javascript, the + operator can also be used to convert a string representation of a number to a number. So the line:

obj.length === +obj.length

can also mean: "length is a number and not a string".

like image 25
slebetman Avatar answered Nov 08 '22 10:11

slebetman