When is obj.length not + obj.length?

I was browsing underscore.js annotated source when I came across this:

if (obj.length === +obj.length) {...} 

Now, I know from https://stackoverflow.com/a/26690/49/ that the plus sign operator (+) returns a numerical representation of the object.

However, obj.length returns a number. When will obj.length not be +obj.length ?

+6
source share
2 answers

When, for example:

 var obj = { 0: 'first', length: '1' }; alert(obj.length === +obj.length); 

Underscore each is common, so it can work with objects other than array . Same as ECMA5 forEach

The forEach function is intentionally shared; it does not require this value to be an Array object. Therefore, it can be passed to other types of objects for use as a method. Whether the forEach function can be successfully applied to the host object is implementation dependent.

So, underlining checks the correctness of the property of the length object. And they consider the arrayLike object for this iteration method only if the length object returns number , which is not NaN , and, of course, is not string . Thus, in my example above, obj will fall into its keys iteration if there is no native / polylized forEach .

+1
source

The === operator does not perform any tricks when checking it, so various data types immediately return false, even if '5' == 5 . + , as you said, prints the object to a number. If you select a number as a number, it is still a number, so you basically check to see if object.length and whether the number is. Values ​​like undefined , NaN , null , string and others are returned false . You do not know what happens with obj, so you need to check ...

+5
source

All Articles