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