What is a block statement in JavaScript?

A block statement groups zero or more statements within curly braces {}. In languages other than JavaScript, it is known as a compound statement. Block statements are commonly used with control structures like if, for, and while.

Syntax

Here's the basic syntax:

{
   // List of statements
   statement1;
   statement2;
   // ...more statements
}

Block Scoping with var vs let/const

Variables declared with var do not have block scope - they are function-scoped or globally-scoped. However, let and const are block-scoped.

Example: var Has No Block Scope

var a = 20;
{
   var a = 40;  // Same variable as outer 'a'
}
console.log(a);  // Prints 40, not 20
40

The inner var a reassigns the outer variable because var ignores block boundaries.

Example: let and const Have Block Scope

let x = 20;
{
   let x = 40;  // Different variable, block-scoped
   console.log("Inside block:", x);
}
console.log("Outside block:", x);
Inside block: 40
Outside block: 20

Common Use Cases

Block statements are frequently used with control structures:

let score = 85;

if (score >= 80) {
   console.log("Grade: A");
   console.log("Excellent work!");
}

for (let i = 0; i < 3; i++) {
   console.log("Iteration:", i);
}
Grade: A
Excellent work!
Iteration: 0
Iteration: 1
Iteration: 2

Conclusion

Block statements group code within curly braces. Use let and const for proper block scoping, as var ignores block boundaries and can lead to unexpected behavior.

Updated on: 2026-03-15T22:05:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements