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.
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.
The plus operator converts a value to Number.
Basically, a === +a
makes sure a is a number and not a string.
It converts a value to a number. I found this article helpful:
http://www.2ality.com/2012/01/object-plus-object.html
Cheers! :)
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