JavaScript Code Blocks
Understanding block scope and code organization
🧱 What are Code Blocks?
Code blocks in JavaScript are sections of code enclosed in curly braces {}. They group statements together and create their own scope.
// This is a code block
{
let message = "Hello from block!";
console.log(message);
}
Output:
Hello from block!
Key Block Concepts
Block Scope
Variables declared inside blocks are local
{
let x = 10;
}
// x is not accessible here
Organization
Group related code together
{
// User data processing
let name = "John";
let age = 25;
}
Control Flow
Used in if, for, while statements
if (true) {
console.log("Inside block");
}
Isolation
Prevent variable name conflicts
{
let temp = 5;
}
{
let temp = 10; // Different variable
}
🔹 Block Scope vs Function Scope
Understanding the difference between block and function scope:
function example() {
var functionScoped = "I'm function scoped";
{
let blockScoped = "I'm block scoped";
const alsoBlockScoped = "Me too!";
var stillFunctionScoped = "I'm still function scoped";
console.log(blockScoped); // Works
}
console.log(functionScoped); // Works
console.log(stillFunctionScoped); // Works
// console.log(blockScoped); // Error!
}
example();
Output:
I'm block scoped
I'm function scoped
I'm still function scoped
🔹 Practical Block Examples
Common uses of code blocks in JavaScript:
// 1. Conditional blocks
let weather = "sunny";
if (weather === "sunny") {
let activity = "go to beach";
console.log("Let's " + activity);
}
// 2. Loop blocks
for (let i = 0; i < 3; i++) {
let message = `Count: ${i}`;
console.log(message);
}
// 3. Standalone blocks for organization
{
// Configuration section
const API_URL = "https://api.example.com";
const TIMEOUT = 5000;
console.log("Config loaded");
}
{
// Data processing section
let data = [1, 2, 3];
let processed = data.map(x => x * 2);
console.log("Data:", processed);
}
Output:
Let's go to beach
Count: 0
Count: 1
Count: 2
Config loaded
Data: [2, 4, 6]
🔹 Block Scope with let and const
let and const create block-scoped variables:
console.log("=== Block Scope Demo ===");
{
let blockVar = "I'm in a block";
const blockConst = "Me too!";
console.log(blockVar);
console.log(blockConst);
}
// These will cause errors if uncommented:
// console.log(blockVar); // ReferenceError
// console.log(blockConst); // ReferenceError
// But var behaves differently:
{
var functionVar = "I escape the block!";
}
console.log(functionVar); // This works!
Output:
=== Block Scope Demo ===
I'm in a block
Me too!
I escape the block!