Why does “a + + b” work, but “a++b” doesn't?

后端 未结 7 973
感情败类
感情败类 2020-12-24 05:35

I was fiddling around with different things, like this

var a = 1, b = 2;
alert(a + - + - + - + - + - + - + - + b); //alerts -1

and I could

7条回答
  •  别那么骄傲
    2020-12-24 06:23

    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.

提交回复
热议问题