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.
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
It does two tests at once:
Can also be written as:
(typeof obj.length === 'number') && !isNaN(obj.length)
Updated answer: I first said it was equivalent to typeof obj.length === 'number') && isFinite(obj.length)
but it isn't since it returns true for +Infinity
and -Infinity
. Thanks to RobG for pointing that out
The unary plus operator (+
) converts the RHS into a Number.
This is a test to see if the value is a Number in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With