Everyone knows how pitiful the syntax of JavaScript is.
Let’s take a picture first
The code is as follows:
Such a painful syntax pit is probably only found in weird things like JavaScript.
I believe that most children who do not study JavaScript compilers cannot understand it at all. (At least I find it incredible)
Later, I went to visit my mother for a special visit, and I suddenly realized it!
Next, let’s take a look at this code:
I believe that most children's shoes will think that this is an object direct quantity at first glance.
What about this code?
Will the browser prompt a syntax error?
Obviously not! If we think about it carefully, we will realize that this is a statement block.
How does the JavaScript compiler deal with this ambiguity?
To solve this problem, ECMA’s method is very simple and crude: during grammar parsing, if a statement starts with "{", it will only be interpreted as a statement block.
This is really a cheating way to deal with it!
Since they are all statement blocks, why does {a:1} have no grammatical errors?
In fact, here, a is understood by the parser as a tag. Labels are used with break and continue statements to make directional jumps.
Therefore, writing like this will throw an exception:
Because function () {} is not a function declaration, nor a function expression.
At this point, everyone should have a basic idea of the strange processing of {}. Let’s look back at the sentences mentioned at the beginning of the article:
The first one, because {} is a statement block, the code can be understood as:
So the return value is 0 .
Second, since {} is not at the beginning of the statement, it is a normal object direct quantity. The empty array and the empty object are added directly and "[object Object]" is returned.
Understood the first and second items, the third item no longer needs explanation.
The fourth one, because it starts with (), the first {} is parsed as an object literal, so the two formulas are equal and return true.