Alex Rivera | Logout

obj.length === +obj.length in javascript

Asked 2012-02-08T06:57:12.097
28

In underscore.js source in many places I came across

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

Can someone explain, why do they use it?

Edit
Report

1 Answer

31

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.

answered 2012-02-08T07:01:43.870

Your Answer