cannot use + when try to add number

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.

Leave a Comment