28

In underscore.js source in many places I came across

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

Can someone explain, why do they use it?

Tamil
  • 5,260
  • 9
  • 40
  • 61

4 Answers4

32

It's another way of writing if (typeof obj.length == 'number'). Why they do it that way, it's anyone's guess. Probably trying to be clever at the expense of readability. Which is not too uncommon these days, unfortunately...

Although it might be so that it can be compressed more by minifiers (YUI Compressor, Closure Compiler, UglifyJS, etc):

(a.length===+a.length) vs (typeof a.length=='number')

Doing it their way would save 5 bytes, each instance.

brianreavis
  • 11,562
  • 3
  • 43
  • 50
  • Save 5 bytes at the expense of some perf though (in chrome anyway) http://jsperf.com/obj-length-vs-typeof-number – j03m May 30 '14 at 18:02
25

This tests if obj's length property is a number.

The unary + operator converts its operand to a number, and the strict equality operator compares the result with the original length property without performing type coercion.

Therefore, the expression will only be true if obj.length is an actual number (not e.g. a string that can be converted to a number).

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
4

I think the main reason they are testing if obj.length is a number - is to differentiate obj type of Object from [object Array] (it would work also with String and Function objects). The [object Object] has no length property.

so if

obj = {a:1, b:2}; //obj.length = undefined

obj.length === +obj.length
undefined === NaN //false - you know that your obj has type Object
// (or some other object, but not Array, !String and !Function)
// so, you need to determine size of the obj in some way
// or use for in loop to iterate over your obj

regards

P.S.: IMO it answers the second part of the "why do they use it" question

Irishka
  • 1,136
  • 6
  • 12
  • thanks, it helped me understand why they needed the "else" clause on this test (which use a "for...in" loop instead of a classical "for" to loop over object keys/item). – Guillaume Gendre Feb 21 '13 at 09:30
2

+obj.length turn obj.length to number. I think this is to test whether obj.length is a number.

xdazz
  • 158,678
  • 38
  • 247
  • 274