Back to course

Scope 102: Block Scope ('let' and 'const')

JavaScript: The Complete '0 to Hero' Beginner Course

48. Scope 102: Block Scope

Block scope is a concept introduced with let and const in ES6, which significantly improved JavaScript's scoping rules.

What is a Block?

A block is defined by any set of curly braces {} (e.g., inside if statements, for loops, or just standalone).

Variables declared with let or const are scoped to the nearest enclosing block.

Block Scope in Practice

javascript let globalCount = 1;

if (true) { let blockCount = 5; // Scoped only to this if block var varCount = 10; // Function-scoped (or globally scoped if outside a function)

console.log(globalCount); // OK: Can access outer scopes
console.log(blockCount);  // OK

}

// console.log(blockCount); // ERROR: blockCount is not defined outside the block.

console.log(varCount); // OK: var 'leaks' out of the block. (Avoid using var!)

Summary: Always use let and const to enforce predictable block scoping, which is essential for writing robust code.