let/const Hoisting
let/const Hoisting
Section titled “let/const Hoisting”Introduction
Section titled “Introduction”let and const are hoisted (they do exist in memory during the creation phase), but they are NOT initialized until the actual declaration is reached. This period between scope entry and declaration is called the Temporal Dead Zone (TDZ).
The Key Insight
Section titled “The Key Insight”// ❌ ReferenceError: Cannot access before initializationconsole.log(myLet);let myLet = 10;
// myLet IS hoisted — it exists in memory// BUT it's in the TDZ — accessing it throws an error// This is different from var (which returns undefined)Block Scope
Section titled “Block Scope”let and const are block-scoped — they only exist within the nearest {}:
if (true) { let x = 10; const y = 20; console.log(x); // 10 console.log(y); // 20}console.log(x); // ReferenceErrorconsole.log(y); // ReferenceErrorTDZ in Practice
Section titled “TDZ in Practice”// TDZ exists from scope start to declaration{ // TDZ starts here for x // console.log(x); — would throw ReferenceError let x = 10; // TDZ ends here console.log(x); // ✅ 10 — after TDZ}
// typeof is also affected{ // console.log(typeof x); // ReferenceError! let x = 10;}const Must Be Initialized
Section titled “const Must Be Initialized”let a; // ✅ OK — undefineda = 10;
const b; // ❌ SyntaxError: Missing initializerconst c = 10; // ✅ OKSummary
Section titled “Summary”| Aspect | let | const |
|---|---|---|
| Hoisted | ✅ Yes | ✅ Yes |
| Initialized | ❌ No (TDZ) | ❌ No (TDZ) |
| Scope | Block | Block |
| Reassignment | ✅ | ❌ |
| Must initialize | ❌ | ✅ |