Course contentsShow
← JavaScript
Lesson 80 of 2,7233. Variables and ScopeFree lesson

Block Scope Basics

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

Block Scope Basics

What you'll learn: How let and const create variables that only exist within their surrounding curly braces.

What is Block Scope?

You've learned that var creates function-scoped variables. But let and const work differently—they're block-scoped, meaning they only exist within the nearest set of curly braces {} that surrounds them.

A block is any section of code wrapped in curly braces. The most common blocks you'll see are:

  • if statements
  • for loops
  • while loops
  • Standalone blocks (just {} on their own)

How Block Scope Works

When you declare a variable with let or const inside a block, that variable only exists inside that block. Once the closing } is reached, the variable is gone.

if (true) {
  let message = "I'm block-scoped!";
  console.log(message); // Works fine
}

console.log(message); // ReferenceError: message is not defined

The message variable dies at the closing brace. It never existed outside that if block.

The Analogy

Think of block scope like rooms in a house. Variables declared with let or const are like furniture placed in a specific room—they only exist in that room. Once you leave the room (close the }), that furniture isn't accessible anymore.

Why This Matters

Block scope prevents variables from leaking into surrounding code where they're not needed, making your code safer and easier to understand. You don't have to worry about accidentally reusing variable names across different blocks.

Key Takeaway: Variables declared with let and const are scoped to the nearest enclosing block {...}, not the entire function or global space.