Block, Scope
Block
In JavaScript, a block is defined using a pair of curly braces {}
. Any code enclosed within these braces is considered part of the block. Blocks can contain one or multiple statements, and are often used to group code logically, especially within conditionals and loops.
A statement is a complete instruction that performs an action, such as declaring a variable, running a loop, or making a decision. Statements are often composed of expressions, which are fragments of code that produce a value—like arithmetic operations (2 + 3
), logical comparisons (x > 10
), or function calls. While expressions return values, statements execute actions using those expressions.
In JavaScript, statements can be terminated in three ways:
Semicolon ;
Scope
Every block {}
in JavaScript creates a new scope, especially when using let
, const
, or class
. This means variables declared inside a block are only accessible within that block. This behavior is different from var
, which is function-scoped. Blocks following control structures like if
, for
, and while
are common places where block scopes are used.
Behind the scenes, when a new scope is created, JavaScript sets up a new Lexical Environment, which is a conceptual structure consisting of two parts:
A Variable Environment, which holds all local variable bindings for that scope.
A reference to an Outer Lexical Environment, which connects it to its parent scope, forming a chain of scopes used during variable lookup.
Understanding how blocks define scopes and how the Lexical Environment works is fundamental to writing predictable and bug-free JavaScript code.
Types of Scope in JavaScript
JavaScript uses a lexical scoping model, meaning that the accessibility of variables is determined by their physical location in the source code. There are three main types of scope in JavaScript:
Global Scope
let globalVar = "I am catfather"; function showGlobal() { console.log(globalVar); // Accessible }
Block Scope
{ let catfather= 100; console.log(catfather);// Accessible } console.log(catfather) // ReferenceError
Function Scope
function greet() { let name = "Catfather"; console.log(name); // Accessible here } console.log(name); // ReferenceError: name is not defined
It's important to note that
var
is function-scoped, but not block-scoped, which can lead to unexpected behaviors.
Last updated