+ 4

JavaScript adding

How do you actually add? because I have this kind of script: var number = window.prompt ("Please Enter a number); var number2 = window.prompt ("Please enter another number"); var sum = number + number2 window.alert (sum) but instead of printing the sum, it just prints the two numbers together. for example, if number and number2 were both equal to 1 instead of saying 2, which is 1+1 it would say 11. I skimmed through the math operators during the lessons, but I couldn't seem to find anything Thanks!

13th Apr 2017, 4:07 PM
Dillion Piazza
Dillion  Piazza - avatar
4 Answers
+ 5
this is better. Try like this. var sum = eval(number) + eval(number2);
13th Apr 2017, 4:18 PM
Yasiru Nayanajith
Yasiru Nayanajith - avatar
+ 5
Try: sum = parseInt(number) + parseInt(number2) It should work for you.
13th Apr 2017, 4:10 PM
Ashwani Kumar
Ashwani Kumar - avatar
+ 3
Thank you For Answering Guys :)
13th Apr 2017, 6:01 PM
Dillion Piazza
Dillion  Piazza - avatar
+ 2
if u use just "parseInt" then number just converted to integer. But using "eval" u will be able to add any kind of number such as int, float, double. So, It will be best to use "eval" instead of "parseInt". var sum= eval(num1)+eval(num2);
13th Apr 2017, 4:34 PM
Md. Jahidul Islam
Md. Jahidul Islam - avatar