Why is 1 + + + 1 = 2 in Javascript?
What is this behavior called? Is it documented somewhere?
Thanks.
Why is 1 + + + 1 = 2 in Javascript?
What is this behavior called? Is it documented somewhere?
Thanks.
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.