How to understand "if ( obj.length === +obj.length )" Javascript condition statement?
- by humanityANDpeace
I have run across a condition statement which I have some difficulties to understand. It looks like (please note the +-sign on the right-hand-side) this:
obj.length === +obj.length.
Can this condition and its purpose/syntax be explained?
Looking at the statement (without knowing it) provokes the impression that it is a dirty hack of some sort, but I am almost certain that underscore.js is rather a well designed library, so there must be a better explanation.
Background
I found this statement used in some functions of the underscore.js library (underscore.js annotated source).
My guesswork is that this condition statement is somehow related to testing for a variable obj to be of Array type? (but I am totally unsure). I have tried to test this using this code.
var myArray = [1,2,3];
testResult1 = myArray.length === +myArray.length;
console.log( testResult1 ); //prints true
var myObject = { foo : "somestring", bar : 123 };
testResult2 = myObject.length === +myObject.length;
console.log( testResult2 ); //prints false