Cybrix
Cybrix

Reputation: 3318

What is unary + used for in Javascript?

I have found some code from Underscore.js

  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    if (obj.length === +obj.length) results.length = obj.length;
    return results;
  };

I would like to know what if (obj.length === +obj.length) does?

Upvotes: 15

Views: 7276

Answers (4)

dinesh_malhotra
dinesh_malhotra

Reputation: 1877

I will suggest you to try this

console.log(typeof +"3") = number

console.log(typeof "3") = string

This makes everything clear.

Upvotes: -1

mrtsherman
mrtsherman

Reputation: 39872

That's the unary + operator. This website has a great article on its uses with the different data types in javascript.

http://xkr.us/articles/javascript/unary-add/

I'll steal the introduction, but it is really worth reading if you are into javascript.

In JavaScript it is possible to use the + operator alone before a single element. This indicates a math operation and tries to convert the element to a number. If the conversion fails, it will evaluate to NaN. This is especially useful when one wants to convert a string to a number quickly, but can also be used on a select set of other types.

The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number. Thusly, the unary + operator can successfully convert many of the native JS types with certain restrictions:

Upvotes: 6

Rob W
Rob W

Reputation: 348992

+length is a method to convert anything to a number.

If it's a number, the value doesn't change, and the comparison returns true.
If it's not a number, the assertion is false.

Upvotes: 12

nothrow
nothrow

Reputation: 16168

This is test, if obj.length is number.

Doing arithmetic operation on string converts it to integer (and + is unary operation.. which doesn't do anything :-) ), and === operator does type-wise comparsion

a === b <=> (a == b) && (typeof a) == (typeof b)

Upvotes: 2

Related Questions