I don\'t understand why JavaScript works this way.
console.log(\"1\" + 1);
console.log(\"1\" - 1);
The first line prints 11, and the second
According to the standard EcmaScript 262. The +
and -
operators behave differently when strings are involved. The first converts every value to a string. The second converts every value to a number.
From the standard:
If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
This rules implies that if in the expression there is a string value, all values involved in the +
operation are converted to a string. In JavaScript when the +
operator is used with strings, it concatenates them. This is why console.log("5"+1)
returns "51". 1
is converted to a string and then, "5" + "1" are concatenated together.
Nevertheless, the above rule doesn't apply for the -
operator. When you are using a -
all values are converted to numbers according to the Standard (see below). Therefore, in this case, "5"
is converted to 5
and then 1
is subtracted.
From the standard:
5 Let lnum be ToNumber(lval).
6 Let rnum be ToNumber(rval).
Operator + : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1
Operator - : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2