The +
operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1'
or '1' + 1
the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The -
operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.
I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.
(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)
If you want to make sure that the +
operator acts as an addition operator, you can explicitly cast values to a number
first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number
equivalents: parseInt()
and parseFloat()
respectively:
const x = 10;
const result = x + parseInt('1'); // 11
const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5'); // 6
Edit
As jcaron states in the comment below, the +
operator has a third meaning in the form of an unary + operator. If +
only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat
does it:
+ '1'; // returns 1
+ '1.5'; // returns 1.5
// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5
Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:
parseFloat('1.5no-longer-valid'); // 1.5
+ '1.5no-longer-valid'; // NaN