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!
It’s checking if the
lengthproperty is numeric. When the unary+is applied, it will return the numeric representation of an object orNaN, which will be the basis for which the comparison will pass or fail. For the first case, ifobjdoesn’t have alengthproperty it will be+undefinedwhich will returnNaN. And ifobj.lengthis numeric, the condition will pass.