cheekyman101
cheekyman101

Reputation: 9

How can I add 2 variables' numerical values together in Javascript

When I do: var answer=a+b

if a was 4 and b was 5 then my answer comes out as 45. How can i get them to numerically add. I can do all other operations(*/-) but not add. Ik its a stupid question but im new and trying to lean

var prea,a,answer2,answer4,answer3,b,preb,answer1;

prea=document.getElementById("form1") ;
a=prea.elements["first"].value;
preb=document.getElementById("form1") ;
b=preb.elements["second"].value;
answer1=a*b;
answer2=a-b;
answer3=a/b;
answer4=a+b;
document.write("Multiplication:"+answer1); 
document.write("<br>");
document.write("Subtraction:"+answer2);
document.write("<br>");
document.write("Division:"+answer3);
document.write("<br>");
document.write("Add:"+answer4);

Upvotes: 0

Views: 127

Answers (2)

cchoe1
cchoe1

Reputation: 389

The variables are being declared as strings. You need to type cast them as an integer value to properly add them using parseInt(string).

The reason all the other operators work is because they will try to type juggle. However, javascript uses + for both numerical addition and string concatenation. So you have to explicitly use integer types if you want the result to be a summation.

Upvotes: 0

Tyr
Tyr

Reputation: 2810

Use Number(a) + Number(b) to calculate them. If you using strings instead of numbers, you just concatinate them instead of adding.

https://www.w3schools.com/jsref/jsref_number.asp

Upvotes: 1

Related Questions