Can I use curly braces in javascript to separate sections of code
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
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/
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";
}
}