+ 1

Problem with JavaScript that I can't seem to figure out solution to...

I wrote a calculator using JavaScript from code off the top of my head (no cheating by looking at other ways people have done it). I have almost completed the script, but for some reason, the addition portion WILL NOT WORK. If you select "addition"(or "1"), it just puts the two numbers chosen together(ex. numOne = 2, numTwo = 4, Result = 24). I have posted the script to the code playground, with hopes that somebody can help me figure out where I messed up. Lol. I'm still new to using JavaScript, so please be easy on me if it's something stupid easy. Haha. =P Calculator Script link : https://code.sololearn.com/W2WsyT4JbGol

8th Dec 2017, 5:58 AM
Andrew T$
Andrew T$ - avatar
4 ответов
+ 4
Try this return +numOne + +numTwo;
8th Dec 2017, 6:18 AM
Calviղ
Calviղ - avatar
+ 4
The problem is your concatenating instead of performing an addition operation due to the numbers being strings. prompt returns a string. Wrap your number prompts with parseFloat() to convert them to floating point numbers. if (operatorChoice !== null) { var numOne = parseFloat(prompt("Enter the first digit! : ")); var numTwo = parseFloat(prompt("Enter the Second digit! : ")); } The other operators -, /, * all work due to JavaScript doing an implicit conversion for you since it can infer that you intend to do a mathematical operation. The reason Calvins hack of using +numOne + +numTwo works is also due to this implicit conversion. It is the same as (1 * numOne) + (1 * numTwo) where the multiplication will convert the strings to a Number type.
8th Dec 2017, 6:54 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Append a "+" in front of a string variable would convert the variable to number. Please note that all the prompt inputs are in string format, even though the input us numeric, it's numerical string. You could use parseFloat function too as what did @ChaoticDawg mention.
8th Dec 2017, 8:58 AM
Calviղ
Calviղ - avatar
+ 3
Thank you Calvin!! Can you explain why my code works for other functions but not for the addition?? :o
8th Dec 2017, 6:42 AM
Andrew T$
Andrew T$ - avatar