4

Reading through the source code of underscore.js I stumbled upon the following line:

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

That's a bit confusing for me. What is actually being compared here? I believe it has something to do about detecting native arrays, but cannot figure out what's actually going on. What does the + do? Why use === instead of ==? And what are the performance benefits of this style?

Saintali
  • 4,482
  • 2
  • 29
  • 49

3 Answers3

6

The + coerces the value to an Number (much like !! coerces it to a boolean).

if (x === +x)

...can be used to confirm that x itself contains an integer value. In this case it may be to make sure that the length property of obj is an integer and has not been overwritten by a string value, as that can screw up iteration if obj is treated as an array.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

It is a silly (IMO) way of checking if obj.length is a Number. This is better:

typeof obj.length == "number"
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

The + coheres what is on the right side to be a number.

In this case if length was not a property on the object undefined would be returned. + undefined will yield Nan and this evalutation be false.

If the string can be coheres-ed into a number then it will be.. e.g + '1' will yield 1 as a Number this is especially important when dealing with hex values in string form e.g. +'0x7070' yields 28784

Jay
  • 3,276
  • 1
  • 28
  • 38