8

Here is some sample code. I'd like to know if there is any reason why I shouldn't do this.

//some code
var x = "hello";

{
    var y = "nice";

    function myfunction() {
        //do stuff . . .
    }
}

The benefit of doing this I see is being able to organize sections of code in chunks and have auto formatters do some work with that...

In my tests {} does not affect the scope when creating a var or function.

Kara
  • 6,115
  • 16
  • 50
  • 57
Jessy
  • 1,150
  • 16
  • 27

5 Answers5

13

This answer was written in times of earlier JavaScript implementations. While the same rules for var apply, ECMAScript 2015 (aka ES6) introduce the let variable declaration statement, which follows "traditional" block-scoped rules.

Example of let scoping with a Block, which logs "1", "2", "1":

{ let x = 1; console.log(x); { let x = 2; console.log(x) }; console.log(x) }

The MDN Reference on Block summarizes the usage of blocks as:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.


As discussed on MDN, the syntax is perfectly valid as { StatementList } (aka Block) is a valid Statement production..

However; and because this is very important: a new block does not introduce a new scope. Only function bodies introduce new scopes. In this case, both the x and y variables have the same scope.

In addition a FunctionDeclaration should appear only as a top-level statement - that is, it must be a statement directly under a Program or Function body, not a Block. In this case the declaration of myfunction is "not reliably portable among implementations".

There is the IIFE (Immediately Invoked Function Expression) pattern which can be used and, while it addresses the technical issues above, I would not recommend it here as it complicates the code. Instead, I would simply create more named functions (named functions can be nested!), perhaps in different modules or objects, as appropriate.

var x = "hello";

;(function () {
   // New function, new scope
   // "y" is created in scope, "x" is accessible through the scope chain
   var y = "nice";

   // Now VALID because FunctionDeclaration is top-level of Function
   function myfunction() {
   }
})(); // Invoke immediately

// No "y" here - not in scope anymore
user2864740
  • 60,010
  • 15
  • 145
  • 220
4

Realize this is old, but figured I would update for ES2015.

The do have a bit more meaning with let + const as found here https://babeljs.io/docs/learn-es2015/

function f() {
  {
    let x;
    {
      // okay, block scoped name
      const x = "sneaky";
      // error, const
      x = "foo";
    }
    // okay, declared with `let`
    x = "bar";
    // error, already declared in block
    let x = "inner";
  }
}
Senica Gonzalez
  • 7,996
  • 16
  • 66
  • 108
  • 2
    Thanks for the follow up, It's interesting to see how a simple question can lead to a lot of community chats about what it means. Learning the rules of how JS gets interpreted helped me grasp lots of more concepts like the {} usage and comma. We have a lot of tricks now with transpiration that use these small nuanced things to minify our code. It's great! – Jessy Sep 04 '20 at 11:45
3

I don't understand the reasoning behind the outermost curly braces, but functions are always written inside curly braces in javascript.

If you are working with other developers they may find the outer curly braces more confusing than helpful and there could be some negative effects : https://web.archive.org/web/20160131174505/http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/

Beau Smith
  • 33,433
  • 13
  • 94
  • 101
Kat
  • 475
  • 1
  • 6
  • 21
  • 1
    Very interesting link. – Lorenz Meyer Oct 24 '13 at 19:29
  • the link broke but this is exactly what I'm going through and wondering what is going on with these code of blocks within curly braces, I'm so confused right now. – eballeste Jul 08 '20 at 21:00
  • essentially, with the exception of the first and last curly bracket, all curly brackets in that code example aren't serving any purpose and should all be removed – Kat Jul 10 '20 at 00:26
0

There are probably many reasons NOT to write code this way... readability is #1, as most would find this makes the code harder to read. However, there is technically nothing wrong with coding like this, and if it's easier for you to read, then it should be fine.

Charlie74
  • 2,883
  • 15
  • 23
  • I agree. Depending on the developers I would be working with I would or wouldn't write code with them. I would hate to see {{{{ var x; }}}} – Jessy Oct 24 '13 at 19:24
0

I think there will be problems with this convention when you start coding more complex programs. There must be a good reason why people don't code like that other than adding extra lines of code.

But since Javascript doesn't have block scoping, the code will still work.

Bazinga777
  • 5,140
  • 13
  • 53
  • 92
  • This was my thinking until reading into some of the links the others posted. It still could be used, but really shouldn't since it'll probably confuse most developers that come across it. Mainly I posted this questions because there was not an answer on Stackoverflow. – Jessy Oct 24 '13 at 19:35