Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In underscore.js source in many places I came across

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

Can someone explain, why do they use it?

like image 546
Tamil Avatar asked Feb 08 '12 06:02

Tamil


Video Answer


2 Answers

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.

like image 151
brianreavis Avatar answered Sep 17 '22 08:09

brianreavis


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).

like image 40
Frédéric Hamidi Avatar answered Sep 19 '22 08:09

Frédéric Hamidi