JS Let
JavaScript let: Block Scope and the Temporal Dead Zone
The let keyword declares a reassignable, block-scoped variable introduced in ES6. Any variable declared with let exists only inside the { ... } block where you define it, such as an if branch or a for loop.
How the Temporal Dead Zone (TDZ) Protects You
Before execution reaches a let declaration, the variable sits in the Temporal Dead Zone. Reading or writing it before its declaration line throws a ReferenceError instead of silently returning undefined.
flowchart TD
Enter["Enter Block Scope"] --> TDZ["Temporal Dead Zone: let count exists but cannot be read"]
TDZ -- "Access before declaration" --> Err["Throws ReferenceError"]
TDZ -- "Reach let count = 0" --> Init["Initialized and ready to read or reassign"]
Block Scope in Practice
Block scoping keeps temporary variables isolated inside if blocks and loops so outer variables never get overwritten by mistake.
let tax = 0.05;
if (true) {
// This 'tax' is a separate variable inside the if-block
let tax = 0.12;
console.log("Local block tax:", tax); // 0.12
}
console.log("Outer tax:", tax); // 0.05
// Each loop iteration gets its own fresh 'i' binding
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log("Iteration index:", i), 10);
}
Why let Fixes the Classic Loop Callback Bug
With legacy var, a for loop shared one single i variable across every callback, so timers printed the final number three times. With let, JavaScript creates a fresh binding on every pass through the loop.
Common Mistakes to Avoid
- Redeclaring the same name in the same block: Writing
let score = 1; let score = 2;in the same block throws aSyntaxError. Reassign withscore = 2;instead. - Accessing
letbefore its line: Movingconsole.log(name)abovelet name = "Kai"causes aReferenceErrordue to the Temporal Dead Zone. - Shadowing outer variables needlessly: Giving an inner
letthe exact same name as an outer variable makes debugging harder. Pick distinct names when possible.
Frequently Asked Questions
What is the Temporal Dead Zone in JavaScript?
The Temporal Dead Zone is the span between entering a block scope and reaching the let or const initialization line. Accessing the variable inside that zone throws a ReferenceError.
Can I declare a let variable without assigning a value?
Yes, let message; is valid and starts as undefined. Unlike const, you do not need to provide an initial value right away.
Does let attach properties to the global window object?
No, declaring let appId = 5 at the top level of a script does not add window.appId, which keeps global scope cleaner than var.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.