This seems quite obvious in its logic (a string can't subtract) but I would like to know how this decision is taken in the underlying execution of JavaScript. How exactly are coercion rules being applied here?
Asked
Active
Viewed 2,522 times
10
-
2It's all in [the language specification](http://www.ecma-international.org/ecma-262/5.1/). See sections 11.6.1 (Addition) and 11.6.2 (Subtraction). Notice that the steps are quite different. – Raymond Chen Sep 17 '14 at 14:16
-
The plus `+` operator is overloaded: when you give it a string (`'1'`) and an int with a `+` sign, it concatenates them (thus you have `11`). It's not possible to do a subtract concatenation, so JavaScript does an actual minus operation, taking both operands to be integers. – Alex Sep 17 '14 at 14:21
-
Related to http://stackoverflow.com/questions/15129137/what-does-mean-in-javascript – Grijesh Chauhan Sep 17 '14 at 14:45
1 Answers
12
-
is defined in terms of ToNumber
, whereas +
has an extra clause for strings (emphasis mine):
11.6.1 The Addition operator (
+
)The addition operator either performs string concatenation or numeric addition.
The production
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingAdditiveExpression
.- Let
lval
beGetValue(lref)
.- Let
rref
be the result of evaluatingMultiplicativeExpression
.- Let
rval
beGetValue(rref)
.- Let
lprim
beToPrimitive(lval)
.- Let
rprim
beToPrimitive(rval)
.- If
Type(lprim)
isString
orType(rprim)
isString
, then
- Return the String that is the result of concatenating
ToString(lprim)
followed byToString(rprim)
[...]

Zeta
- 103,620
- 13
- 194
- 236
-
2I prefer the colouring and styles on [**this**](http://es5.github.io/#x11.6.1) copy of the spec for ease-to-read (it's just personal preference) http://es5.github.io/#x11.6.1 – Paul S. Sep 17 '14 at 14:19