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. Normally, in my experience, curly braces wrap around a function...

function welcome(){ ...

...or a json JavaScript object

var attributes = { this : "that...

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

Djave
  • 6,772
  • 5
  • 54
  • 98
  • 1
    You can wrap block of codes with curly braces, without the need of a variable or function. – Hanlet Escaño Aug 08 '13 at 15:28
  • Yeah, you clearly can as the script runs... I'm just curious as to why its written like that - what does it achieve? – Djave Aug 08 '13 at 15:29
  • 7
    That's not a "JSON object", it's a "JavaScript object". – Rocket Hazmat Aug 08 '13 at 15:29
  • 1
    My guess is that either the author had a function there that was removed and they forgot to take out the brackets, or they think JS has a block-level scope. – JJJ Aug 08 '13 at 15:30
  • 5
    The only reasons for those braces I can find are bad reasons... – Denys Séguret Aug 08 '13 at 15:30
  • 2
    Maybe whoever wrote that thought that JavaScript has block scope (which it doesn't) and was trying to reduce the scope of `s_account`. – go-oleg Aug 08 '13 at 15:31
  • 2
    @RocketHazmat that's not even a JavaScript object. That's just a block. – Florian Margaine Aug 08 '13 at 15:32
  • 1
    It probably helps them to collapse a bunch of variable declarations. – Shmiddty Aug 08 '13 at 15:32
  • 2
    @FlorianMargaine I think rocket was referring to the "or a json object var attributes" – Denys Séguret Aug 08 '13 at 15:32
  • @dystroy: Yep, that's what I was referring to. – Rocket Hazmat Aug 08 '13 at 15:33
  • 2
    alright alright! JavaScript object :) – Djave Aug 08 '13 at 15:35
  • Could be just to isolate the variable declaration, looks weird though. If that's one of the first things, maybe it's declaring a local object to hold local variables, to avoid polluting the global namespace. – Seano666 Aug 08 '13 at 15:36
  • @Seano666: But, JavaScript doesn't have block scope. So the variable is declared in whatever scope the block is in. (The code runs as if the block wasn't there) – Rocket Hazmat Aug 08 '13 at 15:37
  • 2
    In a more classical language with a stricter syntax like C++, such blocks can be used to limit an automatic variable life length, i.E it gets destroy when leaving the block. In javaScript it has no effect. – Virus721 Aug 08 '13 at 15:38
  • Thanks for all the discussion guys... as someone who's come from a design background, not development per se its really interesting to hear – Djave Aug 08 '13 at 15:44
  • `let` and `const` introduced in JavaScript v6 do have block scope, so this now does have more utility, e.g. inside the `case`s of a `switch`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block – alxndr May 18 '16 at 04:59

6 Answers6

16

It's a block and completely pointless unless you label it:

block: {
    var s_account="blog";
    console.log("executed");
    break block;
    console.log("not executed");
}
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Esailija
  • 130,716
  • 22
  • 250
  • 308
11

The only logical reason to do something like this, in my mind, is as an 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 allow you to collapse that "private members" block and get it out of your way.

Shmiddty
  • 13,349
  • 1
  • 32
  • 52
  • Hey, that's a really good point especially about the collapsable side inside an IDE. Its weird, its only a single variable in there though... my other thought is maybe its generated code. – Djave Aug 08 '13 at 15:45
  • The number of variables shouldn't really matter when using a convention. If you are ever going to use the convention, you should *always* use it. – Shmiddty Aug 08 '13 at 15:46
7

It's called a block statement. It lets you group expressions. It's normally used with control structures like if and while, but can also be used on its own.

Since JavaScript doesn't have block scope, the code runs in the same scope (as if the {} weren't there).

Example:

{
    var s_account="blog";
}

console.log(s_account);

That works fine.

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 1
    Only it doesn't allow function declarations inside… – Bergi Aug 08 '13 at 15:37
  • 2
    Read the *Note* on function declarations as [statements](http://es5.github.io/#x12)… Try to call it in FF above the declaration and it'll fail. – Bergi Aug 08 '13 at 15:47
  • 3
    @RocketHazmat "JavaScript doesn't have block scope" - in version <=5 and except for `with` statements and `try/catch`. – Benjamin Gruenbaum Aug 08 '13 at 15:50
7

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

There is no significant point to them in Javascript. It will act exactly the same as if the code was just

var  s_account="blog";
Speculation

In other languages which have block scope, this might restrict the scope of the variable, but since JS doesn't have that feature (for better or worse), braces without a control structure or function are essentially meaningless and ignored.

Most likely this code was left over from a deleted function or if statement however. It definitely is not a pattern to be copied.

Ben McCormick
  • 23,365
  • 11
  • 48
  • 70
  • 5
    Now that we have block scope with let and const this could be useful in some scenarios – Henrik Karlsson Mar 29 '16 at 17:25
  • 2
    The code will act exactly the same. This doesn't mean it's pointless. To follow your logic, are line breaks pointless? Are half of all semicolons in JS pointless? Are comments pointless? As people pointed out below, IDE's and many text editors allow you to collapse block statements. They allow you to segment your code with more than just whitespace. -1 for non-answer when there are valid answers. – RoboticRenaissance Jan 31 '17 at 17:07
7

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • I think your `let foo = "bar";` example still logs `bar`. – Djave Aug 06 '19 at 12:35
  • @Djave - Try it, it's a runnable snippet. :-) The only way it will log `"bar"` is if the JavaScript engine has a broken implementation of `let`. I don't know of any that are broken in that way. (IE9 has an outdated implementation of `let` that fails important use cases related to `for` loops, but IE9 doesn't allow `let` in blocks, so it doesn't log `"bar"` above. [I wasn't sure, so I tried it. :-) ]) – T.J. Crowder Aug 06 '19 at 12:42
  • 1
    Ahhh... I see what I did... I copied and pasted them into the terminal... so the second `console.log` logged the `var` *facepalm* – Djave Aug 06 '19 at 13:22
  • @Djave - LOL! Yup, that explains it. :-D – T.J. Crowder Aug 06 '19 at 13:24
0

Quick addition. In some IDE like Visual Code, putting Curly Braces will actually create a visual block with a 'drop-down' arrow, allowing you to completely hide a portion of code with just a click. It helps with code organization. I'm using it when creating HTML element with a lot of CSS. Since it does not affect code execution, this is very useful.

Séane
  • 91
  • 9