javascript {} block details

  • 2021-01-14 05:33:41
  • OfStack

To study analytic json string, use a eval () method, why you need to add parentheses when parsing a string? It's hard to make sense of it. It turns out that {} blocks in javascript have a semblance of two semantics, which can cause errors without parentheses. Understanding this semblance helps us understand javascript code.

1. Two meanings of a {} block

Representation block

a. In javascript, you can use {} to enclose code to make it easier to manage code in the editor. Because javascript does not have block-level scopes, this notation is harmless.


{
//some code...
}


b. In javascript, conditional statements, loops, and functions all require {} blocks to integrate code

Object literals


var box = {
  name:'kuoaho',
  age:21 
}

[code] is an expression that can be assigned to a variable
// Object literals are expressions that generate object values

2. What happens if an object literal is not an assignment expression?

example:


  {name:'kuoao'}    // No error was reported, but no object was created either 
  {name:'kuohao',age}  // An error 

As can be seen from the above, object literals can only be assigned as expressions. There is nothing wrong with the first method, except that javascript parses it as an label statement.

analysis:


  {name:'kuoao'}

    //{}1 A block 
   // name:'kuohao' . 1 a label Statement for markup for cycle 

3. But here comes the problem...


{
name:'kuohao',
age:21
}

// Why does this report an error? Isn't that how object literals are written?
Because of the 2-sense of {} in javascript, {} is considered not only object literals but also code blocks.


analysis:
  {
  name:'kuohao',
  age:21
  }

One block of code, two label statements, without a comma, is perfectly fine, so the key is the comma, and the two statements should be separated by a semicolon, so javascript will determine that this is a syntax error

4. Correct way to write


({
  name:'kuohao',
  age:21
  })

  // The correct way to write it 

() converts statements into expressions, called statement expressions. Aren't object literals expressions? Why do we need () to transform?

By adding parentheses, this ambiguity is eliminated, because the code inside the parentheses is converted to an expression evaluation and returned, so the block becomes an object literal, and it follows that the object literal must exist as an expression


Related articles: