How is this valid javascript, and what purpose does it serve?

后端 未结 2 550
盖世英雄少女心
盖世英雄少女心 2021-01-26 07:51

I was answering a question on quora and encountered something like following:

// if(true)
{
   var qq = 1;
}

Immediately I fired up chrome and

2条回答
  •  忘了有多久
    2021-01-26 08:12

    It is a block.

    Syntactically, a block is just a bunch of statements that are grouped together.

    Block : { StatementList }
    StatementList
        : StatementListItem
        | StatementList StatementListItem
    StatementListItem
        : Statement
        | Declaration
    

    But here's the tricky part: blocks are statements, too.

    Statement : BlockStatement
    BlockStatement : Block
    

    And there you have it, now you can define compound statements such as if or while in terms of an abstract Statement, without having to worry about whether it is a single statement or a block.

    IfStatement
        : if ( Expression ) Statement else Statement
        | if ( Expression ) Statement
    IterationStatement
        : while ( Expression ) Statement
        | for ( LeftHandSideExpression in Expression ) Statement
        | for ( LeftHandSideExpression of AssignmentExpression ) Statement
    

    Isn't it beautiful?

    As a side effect of this language design, blocks can contain other blocks inside — it isn't worth prohibiting this quirk explicitly in the language specification, although semantically in EcmaScript 5.1 inner blocks were indeed superfluous and very rarely used.

    {
        var x = 1;
        {
            var x = 2; // The same variable as in the outer block.
            console.log(x); //=> 2
        }
        console.log(x); //=> 2
    }
    

    In the latest EcmaScript 6 (2015) standard, however, such blocks do have semantic value, as shown in the next example:

    {
        let x = 1;
        {
            let x = 2; // New variable, visible in this block only.
            console.log(x); //=> 2
        }
        console.log(x); //=> 1
    }
    

    let and const are block-scoped variable declarations introduced by ES6.

提交回复
热议问题