0

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

What is this behavior called? Is it documented somewhere?

Thanks.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

It's parsed as...

1 + (+ (+ 1))

...which obviously evaluates to two.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.