464

What does the +d in

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

mean?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
goh
  • 27,631
  • 28
  • 89
  • 151
  • 1
    possible duplicate of [What does the plus sign do in 'return +new Date'](http://stackoverflow.com/questions/221539/what-does-the-plus-sign-do-in-return-new-date) – nawfal Jan 10 '14 at 12:36
  • 7
    Same issue but the title of other page doesn't describe the general case as this does – geotheory Aug 30 '15 at 10:12
  • 2
    possible duplicate of [What does `+…` mean in JavaScript](https://stackoverflow.com/q/15129137/1048572) – Bergi Aug 08 '17 at 17:02

4 Answers4

520

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.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
  • 14
    Docs: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2b_(Unary_Plus%29 – Felix Kling Jul 13 '11 at 17:27
  • 1
    Working link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_() – Ilker Cat Jan 04 '18 at 22:17
  • I just wonder which is more efficient, parse a string into an integer using the function parseInt or using the plus operator? – acarlstein Jul 23 '18 at 23:24
  • 2
    How is it different from `.parseInt()` ? – Daniel W. Apr 10 '19 at 13:33
  • 14
    @DanielW. 1. `parseInt` will return a whole number, so if you do `parseInt("5.51")` the result would be `5` while `+"5.51"` will give you `5.51`. 2. `parseInt` will *parse* the number from a string and stop at the first non-numeric sign while the unary plus will convert the whole input. So `parseInt("5 bananas") //5` while `+"5 bananas" //NaN` – VLAZ Aug 27 '19 at 10:11
  • @acarlstein whichever it is, I doubt the speed difference actually matters in any meaningful way for the execution of a whole algorithm or even an application. Looking for "efficiency" here is likely a microoptimisation and a premature one at that. – VLAZ Aug 27 '19 at 10:13
  • 1
    @VLAZ I will have to disagree. Its all depending what are you programming and where your code will run. For example, if you investigate, there is a difference in processing time between `i++;` and `++i;`. One thing is if your run your code abrowser, where you have the power of the CPU and memory, and when your code runs, per say, a microcontroller such as Espruino. Sometimes you want to use the less CPU cycles possible. – acarlstein Aug 29 '19 at 21:00
  • @acarlstein it's still premature optimisation. Until you actually find it's a bottleneck, it's not worth spending much time making the numeric conversion faster. And if you are *really* strapped for CPU cycles, then I'd hazard a guess that you shouldn't be running *JavaScript* - an interpreted language. If you still *are* then you have to realise that the interpreter would likely optimise away a lot of cases for you so trying to figure out what is faster is useless when the interpreter turns it all in the same code anyway. `i++` could turn into a straight increment if the value is not used. – VLAZ Aug 30 '19 at 21:20
  • 3
    @acarlstein from the MDN link in the answer: "Although unary negation (-) also can convert non-numbers, **unary plus is the fastest and preferred way of converting something into a number**, because it does not perform any other operations on the number." (just for an "official" answer) – A N Nov 04 '19 at 00:01
92

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);
Jsowa
  • 9,104
  • 5
  • 56
  • 60
  • 2
    Important thing: `1.` and other strings that end with `.` will become fixed by removing the trailing ­`.`. I stumbled upon this when fixing a bug in some real-time input handler that should allow entering decimal numbers but did not work as expected because of `+` operator trimming away the trailing `.`. – JustAMartin Nov 11 '20 at 10:28
  • 3
    Remember to use `+` operator with caution in `if` statements as `NaN` neither equals 'true` or `false`: `if (+function(){ }) console.log('success')` - this will not execute – Kutalia May 20 '21 at 11:08
36

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

naivists
  • 32,681
  • 5
  • 61
  • 85
  • 4
    Please do not add an answer if you are not totally sure what's happening. I got confused by the I believed, please change it if you are sure about it. – Nemesius Nov 18 '21 at 04:58
  • 5
    @Nemesius, good point. The "I believe" part in this answer still holds even though 10 years have passed since I answered it. I am not completely sure, if I can imagine all the possible cases where the two JavaScript "hacks" work the same way. What if `'string'*1` returns something different than `+'string'`? So, it is approximately the same - I believe :) – naivists Nov 24 '21 at 19:33
  • `+1n` throws `TypeError` ("Cannot convert a BigInt value to a number"), whereas `1n*1` throws `TypeError` ("Cannot mix BigInt and other types, use explicit conversions"). A minor difference, but the only one I've found thus far (other than the column placement for the error being different). – Rogue Apr 19 '23 at 13:57
21

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

Example (using the addMonths function in the question):

addMonths(34,1,true);
addMonths("34",1,true);

then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

tozlu
  • 4,667
  • 3
  • 30
  • 44
RubenLaguna
  • 21,435
  • 13
  • 113
  • 151