Details the JavaScript syntax for {} processing of the pit

  • 2020-03-30 03:10:41
  • OfStack

Everyone knows how crappy JavaScript syntax can be.

So let's start with the last picture

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201406/201465101943658.png? 201455101958 ">

The code is as follows:


{} + [];    // 0
[] + {};    // "[object Object]"
{} + [] == [] + {};    // false
({} + [] == [] + {});    // true

This painful syntax pit is probably only available to a JavaScript geek.

I believe that for the vast majority of children who do not study JavaScript compiler, simply can not understand. (at least I don't know)

Later specially went to the baidu once, just a little suddenly enlightened!

Now, let's take a look at this code:


{
    a: 1
}

Believe that most children's shoes, at first glance will think that this is an object of direct volume.

What about this code?


{
    var a = 1;
}

Does the browser prompt for syntax errors?

Apparently not! If you think about it, we'll see that this is a block of statements.


if (isNumber) {
    var a = 1;
}


At this point, the astute you may have noticed that JavaScript that starts with a {can be ambiguous.

So how does the JavaScript compiler handle this ambiguity?

      To solve this problem, ECMA's approach is fairly straightforward: when parsing syntax, if a statement begins with a "{", it is simply interpreted as a statement block.

This is a really bad way to deal with it!

Since they are all statement blocks, why do {a:1} have no syntax errors?

Actually here, a is understood by the parser as a tag. Tags are used with the break and continue statements for directed jumps.

So, this will throw an exception:


{
    a: function () {}
}

Because function () {}  It's not a function declaration, it's not a function expression.

By this point, you should have a basic idea of the weird handling of {}. Let's go back to the first few statements:

The same code at the page code block index 0

First, because {} is a block of statements, the code can be interpreted as:


if (1) {}
+[]

So the return value is 0.

Second, since {} is not at the beginning of the statement, it is a normal direct object quantity, the empty array and the empty object are directly added, returning "[object object]".

With the first, second, and third understood, there is no need to explain.

Fourth, since it is (), the first {} is resolved as an object direct quantity, so the two formulas are equal and return true.


Related articles: