Here is a line of code from underscore. What is that plus prefix for in this line?
if (obj.length === +obj.length) { // plus prefix?
If the object does not have a length
property (being a regular Object
, instead of an Array
), then calling obj.length
will return undefined
. A test for undefined would be clearer, but the implementor chose to first convert it to a number (so it will become NaN
) and then compare it with the original value (using a strict comparison, which will ensure it will yield false
).
Update: as others pointed out, this code seems to be concerned not only with Array
s, but also "array-like" objects (i.e. objects that have a numeric length
property and numeric indices). In such case, a test for instanceof Array
would not be enough (and just testing for undefined
might not be the best option, since there could be a length
but of another type).