0

While I was seeing Underscore.js (version 1.4.3) code, I saw following lines (79 line)

   if (obj.length === +obj.length) {
        for (var i = 0, l = obj.length; i < l; i++) {
            if (iterator.call(context, obj[i], i, obj) === breaker) return;
        }
    }

I didn't understand why + operator used within if statement. (+obj.length)
And, isn't it this statement always true?
I don't think it's a typo. There must be some aim to use that. If anyone knows benefits of this usage, I want to use it in future.
Thanks.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Ikrom
  • 4,785
  • 5
  • 52
  • 76
  • possible duplicate of [What does = +\_ mean in JavaScript](http://stackoverflow.com/questions/15129137/what-does-mean-in-javascript) – Quentin Mar 07 '13 at 12:14

4 Answers4

2

obj.length might be any type - such as undefined. +obj.length is always a number.

So the code basically checks if the length property exists and is a number. The reason for this check is that _.each() accepts both arrays and non-array objects. In case of an array the length property is necessary to iterate over its elements while a for..in loop is the way to go in case of a non-array object.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

The plus operator converts a value to Number.

Basically, a === +a makes sure a is a number and not a string.

Tetaxa
  • 4,375
  • 1
  • 19
  • 25
1

It converts a value to a number. I found this article helpful:

http://www.2ality.com/2012/01/object-plus-object.html

Cheers! :)

Erik Kinding
  • 1,742
  • 2
  • 15
  • 32
1

The unary + operator results in the numeric equivalent of its operand, and NaN if the operand cannot be converted to a number.

It's one of a number of little "tricks" that exist in Javascript:

  • !!foo - converts foo to a boolean
  • ~~foo - converts foo to a 32-bit signed integer
Alnitak
  • 334,560
  • 70
  • 407
  • 495