Block Scope in If Statements
You'll learn how let and const create variables that only exist inside the curly braces of an if/else block, preventing accidental misuse outside.
The Core Idea
When you declare a variable with let or const inside an if statement's curly braces {}, that variable only exists within that block. Once the closing } is reached, the variable disappears from memory. This is called block scope.
Think of it like a private room: what happens inside the room stays inside the room. Once you leave (exit the block), you can't access what was inside anymore.
if (true) {
let message = "I'm inside the block";
console.log(message); // Works fine: "I'm inside the block"
}
console.log(message); // Error! message is not defined
The variable message doesn't exist outside the if block—it was confined to that specific set of curly braces.
Why This Matters
Block scope prevents variables from "leaking" into the rest of your code. Each if/else block gets its own isolated space:
let score = 75;
if (score >= 50) {
let status = "Pass";
console.log(status); // "Pass"
} else {
let status = "Fail"; // Different variable, different block
}
// console.log(status); // Error! status doesn't exist here
Even though both blocks use the name status, they're completely separate variables—each confined to its own block.
Avoiding Confusion
If you need a variable available after the if statement, declare it before the block:
let result;
if (10 > 5) {
result = "Math works!";
}
console.log(result); // "Math works!" - accessible because result was declared outside
Key Takeaway: Variables declared with let and const inside if/else blocks are scoped to those blocks only—they vanish once the block ends, keeping your code clean and preventing accidental reuse.