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 + MultiplicativeExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingAdditiveExpression.- Let
lvalbeGetValue(lref).- Let
rrefbe the result of evaluatingMultiplicativeExpression.- Let
rvalbeGetValue(rref).- Let
lprimbeToPrimitive(lval).- Let
rprimbeToPrimitive(rval).- If
Type(lprim)isStringorType(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