I was fiddling around with different things, like this
var a = 1, b = 2;
alert(a + - + - + - + - + - + - + - + b); //alerts -1
and I could
It's reading a++
, then it encounters a b
and doesn't know what to do with it.
The Javascript parser is greedy (it matches the longest valid operator each time), so it gets the ++
operator from a++b
, making:
(a++) b
which is invalid. When you put in spaces a + + b
, the parser interprets it like this:
(a) + (+b)
which is valid and works out to be three.
See this Wikipedia article on Maximal munch for more details.
Javascript's operator precendence rules for the ++
increment operator has no left-right associativitity. That means a++b
can be interpreted as a++ b
or a ++b
depending on the particular implementation. Either way, it's a syntax error, as you've got 2 variables, one unary-operator, and nothing joining the two variables.
In practical terms:
a = 1
b = 2;
a++ b; -> 2 2
a ++b; -> 1 3
What does 1 3
mean as JS code?
Longest Match rule comes into picture here. It says parser has to take longest token into consideration starting from left to right (I assume Javascript's grammar is Left to Right). So just apply this rule and you will get your answer.
Parser will start from left and will make a, +, + & b separate tokens in case of "a + + b" (due to white space in between them). In case of "a++b" it will apply longest match rule and will create a++ & b as token. a++ b as an expression does not make any semantic sense hence it will not be compiled.
Most programming language parsers tries to get longest chunk of text that make sense, so when Javascript sees:
[a][][][][]
"variable a" - it make sense, let's see next character:
[a][+][][]
"will be adding to varaible a" - it make sense, let's see next character:
[a][+][+][]
"will post-increment variable a" - it make sense, let's see next character,
[a][+][+][b]
This does not make sense. I have two expressions (a++) and (b) and no infix operator between them.
If you make it a+ +b
it will not find the ++
operator and it will work as a + + b
.
This is b/c of the difference in unary operators.
"a + + b" is the same as "a + (+b)"
"a++b" is the same as "(a++) _ b" <--- there is a missing operator where the _ is