Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is unary + used for in Javascript?

Tags:

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?

like image 999
Cybrix Avatar asked Jan 31 '12 15:01

Cybrix


People also ask

What is unary function in JavaScript?

A unary operation is an operation with only one operand. This operand comes either before or after the operator. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed. Operator.

What are unary operator used for?

Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++)

What does unary mean in programming?

A unary operation is an operation with only one operand. As unary operations have only one operand, they are evaluated before other operations containing them. Common unary operators include Positive ( + ) and Negative ( - ).

What is a unary input?

An operation that has only one input. Example: the square root function. √(16) = 4 has just one input "16" to produce an output of 4. There are many more: factorial, sine, cosine, etc.


2 Answers

+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.

like image 194
Rob W Avatar answered Sep 29 '22 20:09

Rob W


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:

like image 40
mrtsherman Avatar answered Sep 29 '22 21:09

mrtsherman