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.
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
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With