let: Block Scope & Temporal Dead ZoneIntroduced in ES6, the let statement declares a re-assignable, block-scoped local variable. Unlike var, let variables cannot be re-declared in the same scope and exist in a Temporal Dead Zone (TDZ) from the start of the block until execution reaches the initialization line.
flowchart TD
Start["Block Entry: { "] --> TDZStart["TDZ Begins (Variable is uninitialized)"]
TDZStart --> AccessAttempt{"Attempt Access Before Line?"}
AccessAttempt -- "Yes" --> Err["ReferenceError: Cannot access before initialization"]
AccessAttempt -- "No" --> Init["let x = 10; (TDZ Ends)"]
Init --> Safe["Safe Usage of x"]
let{} block (e.g., if, for, while, or standalone block).let in the same scope throws a SyntaxError.for (let i = 0; ...) loops, a new binding i is created for every loop iteration.// Demonstrating let scoping, TDZ, and loop binding
// 1. Temporal Dead Zone Demonstration
function demonstrateTDZ() {
// console.log(message); // Throws ReferenceError: Cannot access 'message' before initialization
let message = "TDZ is now over!";
console.log(message); // Safe usage
}
demonstrateTDZ();
// 2. Loop Scope Isolation (let vs var in closures)
console.log("--- Loop with let ---");
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(`let loop iteration: ${i}`); // Prints 0, 1, 2 correctly
}, 100);
}
// 3. Block Shadowing
let status = "Global";
{
let status = "Local Block"; // Shadows outer status variable inside this block
console.log(`Inner Block Status: ${status}`); // Local Block
}
console.log(`Outer Status: ${status}`); // Global
let Before Declaration: Always place let declarations at the top of their enclosing block scope to prevent TDZ ReferenceError crashes.{ ... } blocks or loops so memory can be garbage-collected immediately when the block finishes.Explain why for (let i = 0; i < 3; i++) inside asynchronous callbacks correctly logs 0, 1, 2, whereas for (var i = 0; i < 3; i++) logs 3, 3, 3.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.