The +
and -
symbols are used both as binary infix operators (in addition and subtraction) and as unary prefix operators (unary plus and unary minus). (MDN)
Now, if you have a look at the associativity of the operators, you will note that your expressions are equivalent to the following expressions (with explicit grouping showing the associativity):
5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (2))))))))))))
5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (- (+ (+ 2))))))))))))))
5 - (- (- (1)))
5 - (- (- (+ (1))))
5 - (- (- (+ (- (- (- (- (- (- (- 1))))))))))
5 - (- (- (+ (- (- (- (- (- (- (- (1)))))))))))
console.log('5 + + + + + + + + + + + + 2 === 5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (2)))))))))))): ', 5 + + + + + + + + + + + + 2 === 5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (2)))))))))))));
console.log('5 + + + + + + + + + + + + - + + 2 === 5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (- (+ (+ 2)))))))))))))): ', 5 + + + + + + + + + + + + - + + 2 === 5 + (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (- (+ (+ 2)))))))))))))));
console.log('5 - - - + 1 === 5 - (- (- (+ (1)))): ', 5 - - - + 1 === 5 - (- (- (+ (1)))));
console.log('5 - - - 1 === 5 - (- (- (1))): ', 5 - - - 1 === 5 - (- (- (1))));
console.log('5 - - - + - - - - - - 1 === 5 - (- (- (+ (- (- (- (- (- (- 1))))))))): ', 5 - - - + - - - - - - 1 === 5 - (- (- (+ (- (- (- (- (- (- (1)))))))))));
console.log('5 - - - + - - - - - - - 1 === 5 - (- (- (+ (- (- (- (- (- (- (- (1))))))))))): ', 5 - - - + - - - - - - - 1 === 5 - (- (- (+ (- (- (- (- (- (- (- (1))))))))))));
If you remove the spaces (or parens) in between two +
or -
symbols you will get the pre-increment resp. the pre-decrement operator (++
, --
) for which the above expressions are not valid.
The last line will result in error because *
is not a unary prefix operator.
BONUS: Here's an article on some weird JS math stuff from a blog series which is aptly titled JS WTF. ;-)