Reputation: 139
let at = 1;
console.log(at + - + + + - ++at);
How does this work actually? I will appreciate any help.
Upvotes: 2
Views: 63
Reputation: 1075199
It's not as deep as you probably think it is. :-) It's just this:
console.log(at + ++at);
The series - + + + -
is just a bunch of unary -
and +
. The +
don't do anything (in this case, because they're operating on the result of ++at
which is already a number), and the two -
cancel each other out.
So looking at at + ++at
: The binary +
(addition) evaluates its left hand operand, and then its right-hand operand, and then adds them together (when both are numbers). The left-hand operand is at
, which evaluates to 1
; the right-hand is ++at
, which increments at
to 2
and takes the new value (2
) as its result. So, 1 + 2
= 3
.
We can make it even more confusing by removing optional whitespace, leaving only what's required to differentiate between +
and ++
:
console.log(at+-+ + +-++at);
...but we wouldn't do that to the people coming after us, would we? :-)
If you ever want to see the details of how an expression breaks down, the Esprima folks have a handy page showing the parsing tree of whatever you paste in: http://esprima.org/demo/parse.html
Upvotes: 10