Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is obj.length not equal to +obj.length?

I was perusing the underscore.js annotated source when I encountered this:

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

I now know from this stackoverflow question that the plus sign (+) operator returns the numeric representation of the object.

That said, obj.length returns a number. When would obj.length not be equal to +obj.length?

like image 943
doremi Avatar asked Jan 25 '14 23:01

doremi


1 Answers

The === operator does not make any typecast when it checks, so different types of data will immediately return false even if '5' == 5. The + as you said typecasts the object into number. If you typecast a number into a number, it is still a number, so you basically check if your object.length exists and is a number. Values like undefined, NaN, null, string and others will return false. You are not sure what happens with obj, so you have to check...

like image 50
Theofilos Mouratidis Avatar answered Sep 22 '22 16:09

Theofilos Mouratidis