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

Javascript

Javascript Problem Overview


What does the +d in

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

mean?

Javascript Solutions


Solution 1 - Javascript

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 http://en.wikibooks.org/wiki/JavaScript/Operators">here</a>;. And, as pointed out in comments, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_(.2B)">here</a>;.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongohView Question on Stackoverflow
Solution 1 - JavascriptPaul SonierView Answer on Stackoverflow
Solution 2 - JavascriptJsowaView Answer on Stackoverflow
Solution 3 - JavascriptnaivistsView Answer on Stackoverflow
Solution 4 - JavascriptRubenLagunaView Answer on Stackoverflow