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.
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:
vs