0
let x, y, z;
x = prompt("number 1");
y = prompt("number 2");
z= x + y;
document.write(z)

this is my code and I am just a beginner(I mean literally I know nothing) when I run this page I get the wrong result (12+5 = 125) please help. Multiplication division and subtraction work

Edit: You just need to replace prompt with +prompt

  • 1
    "12" + "5" = "125" ... `prompt` always returns a string. – Teemu Jun 23 '21 at 12:03
  • 1
    `+` defaults to string concatenation when there is at least one string. When using `/` or `*`, it converts the strings to numbers, because there is no operation like these for strings. So just parse your strings to numbers, and you will be fine – MauriceNino Jun 23 '21 at 12:04
  • This might help: https://stackoverflow.com/questions/1133770/how-to-convert-a-string-to-an-integer-in-javascript – MauriceNino Jun 23 '21 at 12:05
  • You are adding two strings together (concatenation). check this [link](https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/) for better explanation – Akhil Jun 23 '21 at 12:05
  • because its treating your input as string so its just joining to number , in order to perform sum you have to change string to number e.g z =num(x) + num(y) add this in you code it will work fine – Milan Jun 23 '21 at 12:20

1 Answers1

2

In javascript the "+" sign is use for addition if the literals are numbers like integers or float values and "+" sign is also use to concat string. So when you take value from prompt then you will receive string value and it will concat x and y instead of addition

So you need to typecast the x and y values to integer then it will work as per your expectations

You can typecast by parseInt() function for integer.

Safe Sahil
  • 46
  • 5