3

I don't understand how the below codes works, can some one help me to understand how this works in JavaScript or why this behaviour ?

  1. 5 + + + + + + + + + + + + 2 = 7 ( If there is no space between operator this will give you error. )
  2. 5 + + + + + + + + + + + + - + + 2 = 3
  3. 5 - - - 1 = 4
  4. 5 - - - + 1 = 4
  5. 5 - - - + - - - - - - 1 = 4
  6. 5 - - - + - - - - - - - 1 = 6. ( If I add one more - then this 6 will become 4, adding - will again change it from 4 to 6 ... 6 to 4)
  7. 5 + + + + + + + + + + + + * + + 2 = This will give you error, so that I can not use multiple * or / in between to numbers.

Please share if there are any other snippets / reference / blog / etc. like this in JavaScript.

NB : I have tested all these things in google chrome console - version 69.0.3497.92 (Official Build) (64-bit)

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
Arun CM
  • 3,345
  • 2
  • 29
  • 35

1 Answers1

4

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. ;-)

FK82
  • 4,907
  • 4
  • 29
  • 42