I came across this line of code in Underscore.js's _.each implementation and I am curious what is going on here. What does the '+' in front of the obj do?
if (obj.length === +obj.length) { ... }
I came across this line of code in Underscore.js's _.each implementation and I am curious what is going on here. What does the '+' in front of the obj do?
if (obj.length === +obj.length) { ... }
The if
tests that obj.length
is numeric and not NaN
. The right-hand side is always a number (or NaN
if obj.length
cannot be interpreted as a number). It will only be ===
to the left-hand side if obj.length
is also a number.
Note that using isNaN
won't work if obj.length
is a numeric-looking string; that is, isNan("3")
returns false
. Note also that NaN === NaN
is false
—NaN
is never ===
to anything.