Home > Article > Web Front-end > Detailed explanation of {} statement block in JavaScript_Basic knowledge
Today I learned to parse a json string and used the eval() method. Why do I need to add parentheses when parsing a string? Puzzled. It turns out that the {} statement block in JavaScript is ambiguous, and an error will occur if parentheses are not added. Understanding this ambiguity is of great help to our understanding of JavaScript code.
1. Two meanings of {} statement block
represents statement block
a. You can use {} to enclose code in javascript to facilitate code management in the editor. Because JavaScript does not have block-level scope, this approach is harmless.
{ //some code... }
b. In JavaScript, conditional statements, loop statements, and functions all require {} statement blocks to integrate code
Object literal
var box = { name:'kuoaho', age:21 }
//At this time [code] is used as an expression and can be assigned to a variable
//In fact, object literals are expressions that can generate object values
2. What happens if the object literal is not used as an assignment expression?
example:
{name:'kuoao'} //没有报错,但是也没有创建对象 {name:'kuohao',age} //报错
As can be seen from the above, object literals can only be assigned as expressions. There is nothing wrong with the first way of writing, but JavaScript parses it as a label statement.
analysis:
{name:'kuoao'} //{}一个语句块 // name:'kuohao',一个label语句,用于标记for循环
3. But the problem comes again...
{ name:'kuohao', age:21 }
//Why does this cause an error? Isn't this how object literals are written?
Because of the ambiguity of {} in JavaScript, {} is not only considered an object literal but also a code block.
analysis: { name:'kuohao', age:21 }
A code block, two label statements, if there is no comma, there is no problem at all, so the key is the comma. The two statements should be separated by a semicolon, so JavaScript will determine that this is a syntax error
4. Correct writing
({ name:'kuohao', age:21 }) //正确的写法
() will convert a statement into an expression, which is called a statement expression. Isn’t an object literal an expression? Why do you need () to convert?
After adding parentheses, this ambiguity can be eliminated, because the code in the parentheses will be converted into expression evaluation and returned, so the statement block becomes an object literal, and it can also be concluded that, Object literals must exist as expressions