10

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?

Nandeep Mali
  • 4,456
  • 1
  • 25
  • 34
  • 2
    It'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 Answers1

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:

  1. Let lref be the result of evaluating AdditiveExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating MultiplicativeExpression.
  4. Let rval be GetValue(rref).
  5. Let lprim be ToPrimitive(lval).
  6. Let rprim be ToPrimitive(rval).
  7. 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)

[...]

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 2
    I 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