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 ?
5 + + + + + + + + + + + + 2 = 7 ( If there is no space between operator this will give you error. )5 + + + + + + + + + + + + - + + 2 = 35 - - - 1 = 45 - - - + 1 = 45 - - - + - - - - - - 1 = 45 - - - + - - - - - - - 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)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)
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. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With