JavaScript curly braces with no function or json

后端 未结 6 819
别那么骄傲
别那么骄傲 2020-12-06 16:16

Just opened a client\'s javascript file and the first lines are along the lines of this:

{
    var s_account=\"blog\";
}

Which I don\'t get

6条回答
  •  猫巷女王i
    2020-12-06 17:01

    That's a block statement. Block statements have multiple purposes, none of which are being used by that code (other than perhaps to group the content together as Shmiddty suggested). (In fact, I'd say in that code they're counter-productive, because for the many people coming to JavaScript from languages where all variable declarations are block-scoped, they create the impression that the variable is scoped to the block, which it isn't.)

    Uses it can have:

    Scoping let, const, and class

    If that code were using let, const, or class, the block would scope the resulting identifier because let, const, and class are block-scoped in JavaScript. So this outputs "bar":

    {
        var foo = "bar";
    }
    
    console.log(foo);

    but this throws a ReferenceError because foo is scoped to the block:

    {
        let foo = "bar";
    }
    
    console.log(foo);

    Providing a block to break

    As Esailija points out, if it were labelled and using break, the break would exit the block early.

    Grouping statements attached to a flow-control statement

    The most common use of a block statement is to group together the statements attached to a flow-control statement like if and for. In this fairly typical if:

    if (something) {
        doThis();
        doThat();
    }
    

    ...the {} aren't part of the if (you can write if without using {}), they're a block statement attached to the if.

提交回复
热议问题