JavaScript adding a string to a number

What you are talking about is a unary plus. It is different than the plus that is used with string concatenation or addition.

If you want to use a unary plus to convert and have it added to the previous value, you need to double up on it.

> 3 + 4 + "5"
"75"
> 3 + 4 + +"5"
12

Edit:

You need to learn about order of operations:

+ and - have the same precedence and are associated to the left:

 > 4 - 3 + 5
 (4 - 3) + 5
 1 + 5
 6

+ associating to the left again:

> 3 + 4 + "5"
(3 + 4) + "5"
7 + "5"
75

unary operators normally have stronger precedence than binary operators:

> 3 + 4 + +"5"
(3 + 4) + (+"5")
7 + (+"5")
7 + 5
12

Leave a Comment