+ 4

What have I done...?

Can anyone help me understand what I did wrong here? Everything works except for addition. https://code.sololearn.com/W3ELnpp0t5Gy/?ref=app

29th Dec 2017, 11:10 PM
Dutch
Dutch - avatar
5 odpowiedzi
+ 5
The values you receive from prompt() are Strings. So, when adding together two Strings: "3" + "5", the result is: "35" rather than 8. Convert the variables x and y (which are supposed to represent numbers) to integers. You can do this with the parseInt() function. Fixed code: var x = parseInt(prompt("Insert first number")); var z = prompt("Choose operator(+,-,*,/)"); var y = parseInt(prompt("Insert second number"));
29th Dec 2017, 11:16 PM
Rrestoring faith
Rrestoring faith - avatar
+ 5
I assume the operators /, - and * try to convert the String to a number. Probably because there is no other use for those operators. Adding on the other hand can be used for both numbers and Strings.
29th Dec 2017, 11:24 PM
Rrestoring faith
Rrestoring faith - avatar
+ 5
Yep, with strings, + is usually used to concatenate two values together. Eg in your code you have this: the plus is concatenating "The sum is " with the value of a. case'+':document.write("The sum is " + a);
30th Dec 2017, 12:40 AM
Duncan
Duncan - avatar
+ 3
@Rrestoring faith Awesome thank you! How did it end up only affecting the addition variable though? O.o
29th Dec 2017, 11:19 PM
Dutch
Dutch - avatar
+ 1
@Rrestoring faith ahhhh ok that makes sense
29th Dec 2017, 11:25 PM
Dutch
Dutch - avatar