0

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

What is this behavior called? Is it documented somewhere?

Thanks.

sarnold
  • 102,305
  • 22
  • 181
  • 238
trivektor
  • 5,608
  • 9
  • 37
  • 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-
  • 218,210
  • 55
  • 464
  • 476
1

It's parsed as...

1 + (+ (+ 1))

...which obviously evaluates to two.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365