Block Scoping in Cases
What you'll learn: How to safely declare let and const variables inside switch cases without causing scope conflicts.
The Hidden Scope Problem
When you write a switch statement, all the case blocks share the same scope by default. This means if you try to declare a variable with let or const in multiple cases, JavaScript will throw an error because you're redeclaring the same variable in the same scope.
switch (day) {
case 'Monday':
let task = 'Meeting'; // First declaration
console.log(task);
break;
case 'Tuesday':
let task = 'Report'; // ERROR: task already declared!
console.log(task);
break;
}
The Solution: Curly Braces Create Scope
Wrap each case block in curly braces {} to create a separate block scope. Now each task variable lives in its own isolated world:
switch (day) {
case 'Monday': {
let task = 'Meeting';
console.log(task);
break;
}
case 'Tuesday': {
let task = 'Report'; // ✓ Different scope, no conflict
console.log(task);
break;
}
}
When You Need This
You only need curly braces when:
- You're declaring variables with
letorconstin cases - Multiple cases might declare variables with the same name
You don't need them if you're just executing statements without declarations, or if each case uses uniquely-named variables.
Key Takeaway: Use curly braces {} around case blocks when declaring let or const variables to create separate block scopes and avoid redeclaration errors.