It is well known to everyone that the syntax of JavaScript is so pitiful.
Let's put up a picture first
The code is as follows:
The code copy is as follows:
{} + []; // 0
[] + {}; // "[object Object]"
{} + [] == [] + {}; // false
({} + [] == [] + {}); // true
Such a painful syntax pitfall is probably only a weird thing like JavaScript.
I believe that most children's shoes that do not study JavaScript compilers cannot be understood at all. (At least I find it incredible)
Later, I went to the Baidu girl for a while and then suddenly realized it!
Let's take a look at this code:
The code copy is as follows:
{
a: 1
}
I believe that most children's shoes will think that this is a direct measurement of the object at first sight.
What about this code?
The code copy is as follows:
{
var a = 1;
}
Will the browser prompt for syntax errors?
Obviously not! If you think about it carefully, we will understand that this is a statement block.
The code copy is as follows:
if (isNumber) {
var a = 1;
}
Speaking of this, you may have discovered that there will be ambiguity in JavaScript starting with {.
So how does the JavaScript compiler deal with this ambiguity?
To solve this problem, ECMA's method is very simple and crude: when parsing syntax, if a statement starts with "{", it is only interpreted as a statement block.
This is really a cheating way!
Since they are all statement blocks, why does {a:1} have no syntax errors?
In fact, here, a is understood by the parser as a tag. Tags are used to match break and continue statements for directional jumps.
Therefore, such a writing method will throw an exception:
The code copy is as follows:
{
a: function () {}
}
Because function () {} is not a function declaration, nor is it a function expression.
At this point, everyone should have a basic concept of the weird treatment of {}. Let’s look back at the few sentences mentioned at the beginning of the article:
The code copy is as follows:
{} + []; // 0
[] + {}; // "[object Object]"
{} + [] == [] + {}; // false
({} + [] == [] + {}); // true
The first one, because {} is a statement block, the code can be understood as:
The code copy is as follows:
if (1) {}
+[]
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.
I understand the first and second articles, but there is no need to explain the third article.
Article 4, because it starts with (), the first {} is parsed into the object's direct quantity, so the two formulas are equal and return true.