2

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

alnafie
  • 10,558
  • 7
  • 28
  • 45

1 Answers1

1

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 falseNaN is never === to anything.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 1
    So what is the point of comparing the same object's .length property, once as a 'forced number' and once not? what does this accomplish? – alnafie Feb 19 '13 at 06:36
  • @alnafie - I'd have to look at the code to know, but my initial guess would be that it's gate around code that either requires that `obj.length` be a number or else some expensive code to calculate `obj.length` that should be skipped if it's already properly set. – Ted Hopp Feb 19 '13 at 06:42