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

Viewed 152956

What does the +d in

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

mean?

4 Answers

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);
Related