Skip to main content
Inspiring
May 18, 2023
Answered

variations using the + sign with adding values

  • May 18, 2023
  • 1 reply
  • 1742 views

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;

This topic has been closed for replies.
Correct answer try67

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

1 reply

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
May 18, 2023

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

ODuinnAuthor
Inspiring
May 18, 2023

Thank you. That 's new to me but I will use it. 

ODuinnAuthor
Inspiring
May 18, 2023

I tried to edit my reply to ask under what circumstances (or why) do you do that, as opposed to apples + oranges + grapes + mangos;