Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a plus symbol before a variable?

Tags:

javascript

What does the +d in

function addMonths(d, n, keepTime) { 
    if (+d) {

mean?

like image 312
goh Avatar asked Jul 13 '11 17:07

goh


People also ask

What is plus before variable JavaScript?

The plus(+) sign before the variables defines that the variable you are going to use is a number variable.

What is the plus (+) sign used to do in Java?

A - The plus sign (+) is automatically overloaded in Java. The plus sign can be used to perform arithmetic addition. It can also be used to concatenate strings. However, the plus sign does more than concatenate strings.

What does before a variable mean?

$ sign before these variable name is just like other characters in variable name. It does not have any significance. You can use this convention to identify that you have jQuery object in this varible. Follow this answer to receive notifications.

What happens if you put a plus sign before a number in Python?

Bookmark this question. Show activity on this post. The question here is the purpose of + in front of a variable. Python docs call it unary plus operator, which “yields its numeric argument unchanged”.


2 Answers

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

like image 192
Paul Sonier Avatar answered Oct 13 '22 03:10

Paul Sonier


Operator + is a unary operator which converts the value to a number. Below is a table with corresponding results of using this operator for different values.

+----------------------------+-----------+
| Value                      | + (Value) |
+----------------------------+-----------+
| 1                          | 1         |
| '-1'                       | -1        |
| '3.14'                     | 3.14      |
| '3'                        | 3         |
| '0xAA'                     | 170       |
| true                       | 1         |
| false                      | 0         |
| null                       | 0         |
| 'Infinity'                 | Infinity  |
| 'infinity'                 | NaN       |
| '10a'                      | NaN       |
| undefined                  | NaN       |
| ['Apple']                  | NaN       |
| function(val){ return val }| NaN       |
+----------------------------+-----------+

Operator + returns a value for objects which have implemented method valueOf.

let something = {
    valueOf: function () {
        return 25;
    }
};

console.log(+something);
like image 66
Jsowa Avatar answered Oct 13 '22 03:10

Jsowa