Lecture Notes: JavaScript Blocks
Key Concepts
What is a Block?
{
...
}
) is used to group multiple JavaScript statements together.
- Also Known As: Compound statement.
- Purpose: To provide a group of statements in places where JavaScript expects a single statement.
Use Cases of Blocks
- Blocks are often used in control flow statements like if-else, for, and while loops to execute multiple statements.
Example
if (condition) {
statement1;
statement2;
// More statements
} else {
statement3;
}
- In this example, the if-else block groups multiple statements under the condition.
Block Scope
- Block Scope: Variables declared inside a block using
let or const are not accessible outside the block.
- Example:
{
let x = 10;
const y = 20;
}
// x and y are not accessible here.
- Variables declared with
var do not honor block scope and are instead function-scoped or globally-scoped.
Hoisting
- Variables declared with
let and const: Hoisted to the block level but not initialized.
- Variables declared with
var: Hoisted to the top of their enclosing function or global context.
Traditional vs Lexical Scoping
- Traditional: Uses function scope (e.g.,
var declarations are hoisted to the function scope).
- Lexical (ES6): Uses block scope (e.g.,
let and const declarations).
Special Considerations
- Shadowing: When you declare a variable inside a block with the same name as one outside the block, the inner variable shadows the outer one within the block.
Example with Shadowing
let a = 5;
{
let a = 10; // Shadows the outer 'a'
console.log(a); // Output: 10
}
console.log(a); // Output: 5
- Shadowing only works within the scope it is declared, meaning the outer variable remains unaffected outside the block.
Functions and Block Scope
- In ES6, functions themselves can be block-scoped if declared within a block.
Summary
- Blocks are essential for organizing code, managing scope, and avoiding variable conflicts through scope isolation (especially when using
let and const).
- Understanding block scope helps avoid bugs related to variable hoisting and scope leakage.