0

The JS spec seems to say two things:

  1. When a number and a string are added, the number is coerced into a string, and the two strings are concatenated. "2" + 7 == "27" and 2 + "7" == "27" are both true.
  2. The + operator is right-associative.

If + is right-associative, then I would expect chained addition operations like 4 + 3 + 2 + "1" to be evaluated like 4 + (3 + (2 + "1")), and for the logic to be

  1. 2 + "1" evaluates to "21"
  2. 3 + "21" evaluates to "321"
  3. 4 + "321" evaluates to "4321"

But instead, the expression evaluates to "91", like it's doing 4 + 3 = 7, 7 + 2 = 9, 9 + "1" = "91".

What have I misunderstood or missed?

GreenTriangle
  • 2,382
  • 2
  • 21
  • 35
  • 10
    Addition is left-to-right associative according to [this table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table). You might be confusing it with unary plus. – John Montgomery Nov 16 '20 at 21:00
  • 2
    _The JS spec seems to say two things ... The `+` operator is right-associative_... where? – Salman A Nov 16 '20 at 21:05
  • @JohnMontgomery is right, I mixed up addition and unary plus, which I was unfamiliar with. My bad. – GreenTriangle Nov 16 '20 at 21:16

0 Answers0