0

Why is 1 + + + 1 = 2 in Javascript?

What is this behavior called? Is it documented somewhere?

Thanks.

sarnold
  • 99,632
  • 21
  • 173
  • 228
trivektor
  • 5,508
  • 9
  • 36
  • 53

2 Answers2

6

It's because of the spacing. The unary operator + can be applied as many times as necessary, and so your expression becomes:

1 + (+(+1))

That is,

1 + 1

. Normally, it appears you can't do this, i.e. 1 + ++ 1 will fail, but that's because two +s are parsed as a prefix increment which is invalid when not used on a variable. In the same way, 1 +++ 1 fails because it's parsed as 1++ + 1, and you can't increment 1.

Ry-
  • 209,133
  • 54
  • 439
  • 449
1

It's parsed as...

1 + (+ (+ 1))

...which obviously evaluates to two.

Marcelo Cantos
  • 174,413
  • 38
  • 319
  • 360