JavaScript curly braces without function or json

Just opened a client javascript file and the first lines go line by line:

{
    var s_account="blog";
}

      

Which I won't get. Usually, in my experience, curly braces wrap around a function ...

function welcome(){ ...

      

... or json JavaScript object

var attributes = { this : "that...

      

Can anyone tell me why there are curly braces with no text before or after them? What does it do / what's the point?

+13


source to share


4 answers


Can anyone tell me why there are curly braces with no text before or after them? What does it do / what's the point?

There is no essential point for them in Javascript. It will act exactly the same as if the code were just

var  s_account="blog";

      



speculation

In other block-scoped languages, this can limit the scope of the variable, but since JS doesn't have this feature (better or worse), curly braces without a structure or control function are essentially meaningless and ignored.

Most likely, this code was left from a deleted function or if statement. This is definitely not a template to be copied.

+7


source


This is a block and completely meaningless if you haven't checked it:



block: {
    var s_account="blog";
    break block;
    alert("not executed");
}

      

+10


source


The only logical reason to do something like this, in my opinion, is organizational technique.

function banana(){
    // private members
    {
        var foo = "foo",
            bar = "bar",
            baz = "baz";

        function bux(){
            console.log("bux");
        }
    }

    // public members

    this.fin = "fin";
    this.fang = "fang";
    this.foom = "foom";

    this.shamalamadingdong = function(){
        bux();
    };
}

      

Also, most IDEs will let you collapse and get rid of this "individuals" block.

+7


source


He named the statement block statement . It allows you to group expressions. It is commonly used with control structures such as if

and while

, but it can also be used on its own.

Since JavaScript has no block scope, the code works in the same scope (as if {}

it wasn't there).

Example:

{
    var s_account="blog";
}

console.log(s_account);

      

This works great.

+5


source







All Articles