0

I have different functions which return values; So i created different function to sum both values.

function result(){
    var result = firstFunct() + secondFunct();
    alert(result);
    return result;
}

And it gives for me a result like joint of two strings: 1010 instead 20. What kind of operator do I need to use two sum both of them?

2
  • 1
    Make sure you return numbers from those functions, not strings, and don't return the alert() function, but the result. Commented Jul 23, 2016 at 20:44
  • Note also that it is confusing to have a variable (result) with the same name as the function. Commented Jul 23, 2016 at 20:46

2 Answers 2

3

This is most probably because your functions are returning string and not a numeric data type. You will need to cast the output of the functions

var result = Number(firstFunct()) + Number(secondFunct());

Note, casting to a number could also be done in a shorter way, using the + operator:

var result = (+firstFunct()) + (+secondFunct());
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works... I been suspicious it is a string. Thanks again!
@MrVitaminasG - could you accept this answer?
I was waiting for countdown to vote. The system not giving to vote straight away
0

To cast to a numeric you can also do:

var num = 1 * numericstring;

4 Comments

Well, +numericString is probably preferable.
This can be mistreated as concatenation.
Mistreated by whom, in what way? The unary plus has exactly one meaning, According to the documentation, "The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already."
I mean syntactic constructs like a + (+b) and even a++b are ugly and prone for errors. These cannot be used in expressions as easily and clearly as 1*a + 1*b.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.