Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand "if ( obj.length === +obj.length )" Javascript condition statement?

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

like image 853
humanityANDpeace Avatar asked Nov 06 '13 09:11

humanityANDpeace


Video Answer


2 Answers

It does two tests at once:

  • Makes sure that obj.length is a number
  • Makes sure that obj.length is not NaN (not a number)

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

like image 148
some Avatar answered Sep 19 '22 22:09

some


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.

like image 24
Quentin Avatar answered Sep 17 '22 22:09

Quentin