2

Possible Duplicate:
javascript: plus symbol before variable
obj.length === +obj.length in javascript

While looking at the source of underscore.js I came across this line (#79)

//some stuff
} else if (obj.length === +obj.length) {
//do stuff

I'm not 100% certain of whats going on here, can anyone explain the purpose of the '+' before the obj.length value?? Would the comparison be identical if it just read:

} else if (obj.length === obj.length) {

The same type of comparison is made multiple times in underscore.js, so I'm fairly certain it's not a typo.

If anyone could point me to an article, or throw some correct terminology at me, I'd appreciate it :). Thanks!

Community
  • 1
  • 1
TuK
  • 3,556
  • 4
  • 24
  • 24
  • 1
    duplicate of http://stackoverflow.com/questions/6682997/javascript-plus-symbol-before-variable. Essentially, it's equivalent to the `Number()` constructor. Check this link for more details: http://stackoverflow.com/questions/4262174/javascript-input-numbers – jeremy Jan 01 '13 at 05:22
  • 2
    Exactly same:: http://stackoverflow.com/questions/9188998/obj-length-obj-length-in-javascript do you even try searching before posting question..? – Sudhir Bastakoti Jan 01 '13 at 05:28

1 Answers1

5

It's checking if the length property is numeric. When the unary + is applied, it will return the numeric representation of an object or NaN, which will be the basis for which the comparison will pass or fail. For the first case, if obj doesn't have a length property it will be +undefined which will return NaN. And if obj.length is numeric, the condition will pass.

David G
  • 94,763
  • 41
  • 167
  • 253
  • This answer is actually wrong (or it may was only correct in the past?). The unary operator does not use the `.length` property on an object. Instead, it uses the `valueOf`key of an object to try to cast it into a number. It works the same as the `Number()` constructor. You can use the unary operator if you want to e. g. convert a string of `"3"`into a number type. – Xen_mar May 09 '21 at 07:25
  • @Xen_mar I meant that the expression `obj.length == +obj.length` is checking if the `length` property is numeric. I didn't mean that the unary plus is checking `length`. Sorry if that was unclear. – David G May 09 '21 at 15:33