cannot use + when try to add number
Solution 1:
Because there is an implicit conversion when you are using +
. In your case +
is actually concatenating the values.
The function prompt returns a string so when you are adding it to an int it is concatenating the values. It takes both the values as string and concatenates the value instead of adding it.
MDN says that:
String operators
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".
You need to cast it like Number(userAmount)
Something like:
var totalMoney = userMoney + Number(userAmount);
or
userAmount = parseFloat(prompt("Amount: "));
so you need to cast both the values to an int so that +
operator behaves as addition instead of string concatenation.
Solution 2:
A common mistake for people new to JavaScript is they forget almost every value taken from user input is a String. You'll need to convert these into numbers before you can use the addition +
operator. This conversion can be done with the unary +
or parseFloat
, for example
userAmount = parseFloat(prompt("Amount: "));
When using Strings in JavaScript, the +
operator is actually string concatenation