During the earlier implementations of JavaScript, this answer was written to explain the differences in variable declarations between using var
and the introduction of ECMAScript 2015 (ES6), which brought about the let
statement for block-scoped variables.
An example is provided to demonstrate scoping with let
within a block.
{ let x = 1; console.log(x); { let x = 2; console.log(x) }; console.log(x) }
The usage of blocks in JavaScript, as summarized by the MDN Reference on Block, does not create block scope. Variables declared within a block are scoped to the containing function or script, persisting beyond the block itself.
Important: The use of standalone blocks in JavaScript does not introduce new scope like in C or Java. Variables remain scoped to the containing function or script.
While syntactically valid, it is crucial to note that creating a new block does not establish a new scope in JavaScript. Only function bodies introduce new scopes, causing variables such as x
and y
to share the same scope.
Function declarations should only appear at the top level of a program or function body, rather than within a block, in order to ensure portability among different implementations.
Instead of using Immediately Invoked Function Expressions (IIFE) to address scope issues, consider creating more named functions to simplify the code structure and maintain accessibility without complicating the implementation.
var x = "hello";
;(function () {
var y = "nice";
// Valid function declaration due to being at the top-level of the function
function myfunction() {
}
})(); // Invoke immediately
// "y" is no longer in scope here