Copy link to clipboard
Copied
I have seen the plus sign used two different ways for adding numbers and have found that when used as in the second example below it can solve the problem of concantenating numbers. I would like to know when it is appropriate to use it as in the second example Say the variables apples, oranges, grapes and mangos each represent a numerical value. I might see these added like this:
(1) var total = apples + oranges + grapes + mangos;
or I might see these added like this:
(2) var total = +apples + +oranges + +grapes + +mangos;
Also, in the second example, is it correct for the first variable, apples, to lead with the + sign, as +applies, or should that line be written like this: var total = apples + +oranges + +grapes + +mangos;
Copy link to clipboard
Copied
It can be done like that, although I find it confusing. I prefer to use the Number operator, like this:
var total = Number(apples) + Number(oranges) + Number(grapes) + Number(mangos);
Copy link to clipboard
Copied
It can be done like that, although I find it confusing. I prefer to use the Number operator, like this:
var total = Number(apples) + Number(oranges) + Number(grapes) + Number(mangos);
Copy link to clipboard
Copied
Thank you. That 's new to me but I will use it.
Copy link to clipboard
Copied
I tried to edit my reply to ask under what circumstances (or why) do you do that, as opposed to apples + oranges + grapes + mangos;
Copy link to clipboard
Copied
Because if the value of one of those variables is not a number, but a string, the result might be a concatenation of all the values, instead of adding them up.
Compare the results of:
1 + 2 + 3 + 4
With:
"1" + 2 + 3 + 4
Or even:
"" + 2 + 3 + 4
Copy link to clipboard
Copied
Thank you again. I was not aware that "" == a string. Important to understand.
Copy link to clipboard
Copied
Everything with double-quotes around it is a string, even if there's nothing between them.